【问题标题】:How to ignore empty array collection in laravel如何忽略laravel中的空数组集合
【发布时间】:2016-01-18 07:39:17
【问题描述】:

您好,我正在尝试从 laravel 5.1 中的关系中获取相关数据,它返回给我一个空数组集合。如何在 laravel 中忽略我的变量中的空数组集合。

 $brandsId = Input::has('brands') ? Input::get('brands') : null;
   $brands = Brand::findMany($brandsId);
   foreach($brands as $brand){
        $products = $brand->products()->paginate(15)//this will return an empty array if it doesnt find aything;
         echo "<pre>";
         print_r( $products);

空数组集合如下所示。

Illuminate\Pagination\LengthAwarePaginator Object
(
    [total:protected] => 0
    [lastPage:protected] => 0
    [items:protected] => Illuminate\Database\Eloquent\Collection Object
        (
            [items:protected] => Array
                (
                )

        )

    [perPage:protected] => 15
    [currentPage:protected] => 1
    [path:protected] => http://localhost:8000/filter
    [query:protected] => Array
        (
        )

    [fragment:protected] => 
    [pageName:protected] => page
)

【问题讨论】:

  • 您可以随时使用count($product) 函数检查它是否为空。除此之外,我无能为力 - 如果我假设您正在尝试在视图中渲染它(或将非空结果放入其他内容)所有非空结果,那么您必须检查它是空的还是不是手动的。

标签: php arrays collections laravel-5


【解决方案1】:

看看isEmpty()

如果集合为空,isEmpty 方法返回 true;否则, 返回 false:

if ($products->isEmpty()) echo "collection is empty"

在收集文档中,您将see all available functions

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 2022-11-16
    • 2015-02-08
    • 2014-05-24
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多