首页 > 解决方案 > 如何在 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',
];

标签: phplaravel

解决方案


你可以解决你的问题,你只需要使用Arr::get助手。它允许使用,例如dot.notation,您可以这样做phone.home在此处阅读更多相关信息。

所以,你的代码应该是这样的:

@foreach ($data as $row)
    <tr>
        @foreach ($columns as $col)
            <td>{{ Arr::get($row, $col) }}</td>
        @endforeach
    </tr>
@endforeach

推荐阅读