php - 如何在 Laravel 集合中获取嵌套值
问题描述
我从数据库中检索到的集合类似于:
$data = [
[
'first_name' => 'John',
'last_name' => 'Doe',
'phone' => [
'home' => 123,
'work' => 456,
'cell' => 789,
]
],
....
];
现在我想把数据放到一个表中,所以table.blade.php
我放了类似的东西
@foreach ($data as $row)
<tr>
@foreach ($columns as $col)
<td>{{ $row[$col] }}</td>
@endforeach
</tr>
@endforeach
我定义$columns
为
$columns = [
'first_name',
'last_name',
'phone.home', // <== I think it cannot access nested value this way, is there any way to do that?
'phone.work',
'phone.cell',
];
解决方案
你可以解决你的问题,你只需要使用Arr::get
助手。它允许使用,例如dot.notation
,您可以这样做phone.home
。在此处阅读更多相关信息。
所以,你的代码应该是这样的:
@foreach ($data as $row)
<tr>
@foreach ($columns as $col)
<td>{{ Arr::get($row, $col) }}</td>
@endforeach
</tr>
@endforeach
推荐阅读
- algorithm - Dijkstra 将图形存储在文本文件中
- python - 如何删除两个 CSV 之间的不常见行?
- javascript - StripeCheckout 未定义错误
- javascript - 注销然后重新加载页面自动登录
- c# - 获取内存可变结构的正确方法
/ 跨度 ? - c# - 从 dotnet core 1 迁移到 dotnet core 2.1 后应用程序变慢
- airflow - 如何更改气流/作曲家的日志级别
- swift - StorageMetadata' 没有成员 'downloadURL'
- java - Xamarin.Android Notification.Notify 什么都不做
- algorithm - 确保独特的 Futoshiki 解决方案的最少线索数是多少?