首页 > 解决方案 > 带有 json 数据 laravel 的 Foreach 循环

问题描述

我想用 laravel excel 用 json 数据在 html 中制作一个表格,数据看起来像这样

4 => {
    +"id": 5
    +"date": "2020-1-3"
    +"grade": "7"
    +"nama": "["bryan","anderson"]"
    +"status": "["active","active"]"
}

我希望的excel文件输出就是 这个状态根据日期填充列,如果没有特定日期的数据,则该列将填充“-”。我尝试了一个在这里找到的 foreach 循环,但没有任何运气。

我用 调用数据$reports,例如$reports->status将返回["active","active"]等。

这是我正在处理的代码

<table>
    <thead>
        <tr>
            <th>No.</th>
            <th>Name</th>
            @for ($i = 1; $i < 32; $i++)
                <th>{{ $i }}</th>
            @endfor
        </tr>
    </thead>
    <tbody>
        @foreach ($reports as $rp)
            <tr>
                <td>{{ $loop->iteration }}</td>
                    <!--INSERT DATA HERE-->
                <td></td>
            </tr>
        @endforeach
    </tbody>
</table>

dd($reports) 返回 =

array:2 [▼
0 => {#455 ▼
    +"id": 17
    +"date": "2021-01-03"
    +"grade": "7"
    +"nama": "["bryan","anderson"]"
    +"status": "["active","active"]"
    +"created_at": "2021-01-23 05:33:27"
    +"updated_at": "2021-01-23 05:33:27"
  }
  1 => {#1414 ▶}
]

标签: jsonexcellaravelforeach

解决方案


Try this following code;
    <table border=1>
                            <thead>
                                <tr>
                                    <th>No.</th>
                                    <th>Name</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php $index=1; @endphp
                                @foreach ($reports as $rp)
                                    @foreach ($rp->nama as $key => $val)
                                        <tr>
                                            <td>{{ $index }}</td>
                                            <td>{{ $val }}</td>
                                            <td>{{ optional($rp->status)[$key] }}</td>
                                        </tr>
                                        @php $index++; @endphp
                                    @endforeach
                                @endforeach
                            </tbody>
                        </table>

推荐阅读