首页 > 解决方案 > 空数组在 Laravel 刀片中不会显示为空

问题描述

现在我正在尝试检查视图何时收到一个空数组。

@if(! empty($array))
    // Section content goes here...

    @foreach($array as $value)
        // All table data goes here... 
    @endforeach
@endif

$array当为空并导致异常时,上面的代码似乎仍在运行。

当我尝试转储数组时,{{ dd($array) }}我得到$array = [].

标签: phplaravel

解决方案


听起来你可能正在收藏。您可以简单count($array)地检查数组中的记录数量。它看起来像这样:

@if(count($array))
    // Section content goes here...

    @foreach($array as $value)
        // All table data goes here... 
    @endforeach
@endif

现在应该隐藏该部分。如果您只想在数组中没有任何内容时跳过 foreach,您可以这样做:

// Section content goes here...

@forelse($array as $value)
    // All table data goes here...
@empty
    // Optional message if it's empty
@endforelse

它将输出部分内容并检查数组之前是否有任何值foreach

你可以在Laravel 文档中阅读更多关于刀片文件中循环的信息。


推荐阅读