首页 > 解决方案 > 在 laravel 中使用数组作为 html 表

问题描述

尝试获取我的数组并将值插入 html 表结构时,我的刀片上出现未定义的索引错误。

我有数组循环并将其发送到刀片:

控制器

$result = array();
foreach($getItem as $Item){
    $result[$Item->item_id][] = $Item;
}

//returning to blade but not included here

转储数组:

array:26 [▼
    11873 => array:2 [▼
        0 => {#407 ▼
          +"item_id": "11873"
          +"item_name": "Title"
          +"item_comment": "Item Title"
          +"item_type": "2"
        }
        1 => {#408 ▼
          +"item_id": "11873"
          +"item_name": "Instruction"
          +"item_comment": "Inst Comment"
          +"item_type": "2"
        }
]

刀:

@foreach ($result as $id => $item)
    <tr>
        <td>{{ $item['item_id'] }}</td>
        @if($item['item_name'] == "Title")
            <td>{{ $item['item_comment'] }}</td>
        @endif
        <td>{{ $item['item_type'] }}</td>
    </tr>
@endforeach

因此,对于转储数组结构,一个问题是“item_type”应该与 id 处于较高级别,而不应该在每个嵌套级别中。但除此之外,我得到未定义的索引错误。我只是循环不正确吗?

标签: phphtmllaravel

解决方案


In @foreach ($result as $id => $item),$item是一个数组,您还需要遍历它。

@foreach ($result as $id => $item)
    <tr>
        <td>{{ $id }}</td>
        @foreach($item as $subitem)
        @if($subitem['item_name'] == "Title")
            <td>{{ $subitem['item_comment'] }}</td>
        @endif
        <td>{{ $subitem['item_type'] }}</td>
        @endforeach
    </tr>
@endforeach

推荐阅读