代码之家  ›  专栏  ›  技术社区  ›  Carlos Salazar

如何知道输入数组元素是否为空?[副本]

  •  0
  • Carlos Salazar  · 技术社区  · 7 年前

    我有一个输入,它是一个数组,数组的键是这样的lang id

    <input type="text" name="name[{{ $lang->id }}]">
    

    name[]

    {
        "1": null,
        "2": null
    }
    

    我做不到

    if($request->has('name')) {
        //do something
    }else {
        //do another thing
    }
    

    $request 有名字,有办法做这样的事吗

    if(array_is_empty($request->has('name'))) {
        //do something
    }else {
        //do another thing
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   ArtisticPhoenix    7 年前

    $IMPLE使用数组筛选器,它将从数组中删除任何空项或虚假项,然后检查是否还有剩余项:

    if(empty(array_filter($array)))
    

    如果您想将空格视为空,例如,有人只在字段中放置空格,您可以使用trim作为回调抛出数组映射,如下所示:

     if(empty(array_filter(array_map('trim',$array))))
    

    测试一下

    $a = [
        "1" => null,
        "2" => null
    ];
    
    if(empty(array_filter($a))) echo 'empty';
    

    输出

     empty
    

    Sandbox

    array_filter 使用回调函数过滤数组的元素 迭代数组中的每个值,并将它们传递给回调函数。如果回调函数返回true,则数组中的当前值将返回到结果数组中。保留数组键。

    0
    "0"
    ""
    false
    null
    [] //this is what you get after filtering $array
    

    可能还有其他的,但这应该给你一个想法。

    因为数组过滤器返回一个空数组 []

    if(!array_filter($array)) 
    

    empty 使用的意图非常清楚。

        2
  •  2
  •   ourmandave    7 年前

    Laravel验证器具有 nullable 对可选字段进行验证的规则。

    https://laravel.com/docs/5.6/validation#a-note-on-optional-fields

    https://laravel.com/docs/5.6/validation#validating-arrays

    所以你可以。。。

     $request->validate([
       'name.*' => 'nullable|string',
     ]);