如何在Laravel中使用数组抽取从多维数组中获取键值?

时间:2019-11-21 10:24:49

标签: arrays laravel

我具有以下多维数组:

[
    {
        "city": {
            "name": "New York",
            "country": "Usa",
            "geolocation": {
                "lat": "40.7142691",
                "lon": "-74.0059729"
            },
        },
        "experiences": [
            {
                "title": "foobar",
                "id": "54095f19ca04fffa8791ecae"
            },
            {
                "title": "foobar_foo",
                "id": "54e1bff02f16a457c00ea171"
            }
            [...]
        ]
    },
    {
        "city": {
            "name": "San Francisco",
            "country": "Usa",
            "geolocation": {
                "lat": "37.7749295",
                "lon": "-122.4194155"
            },
        },
        "experiences": [
            {
                "title": "foobar",
                "id": "53e4db618027d69eab65f2ce"
            },
            {
                "title": "foobar_bar",
                "id": "54afbeb7abdf8e3d30bd5993"
            }
            [...]
        ]
    }
]

我需要创建一个新数组,其中包含上述数组中每种体验的ID,例如:

["id" = "foo123", "id" => "foo456", "id" => "foo789", "id" => "fooabc"] 

我尝试使用laravel的辅助程序Arr::pluck,但它返回null:

Arr::pluck($myArr, "experiences.id")

[null,null,null]

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试

$res = [];
foreach($data as $key => $value)
{
  foreach($value['experiences'] as $exp)
  {
    $res[] = $exp['id'];
  }
}
dd($res);

输出将为

array:4 [
0 => "54095f19ca04fffa8791ecae"
1 => "54e1bff02f16a457c00ea171"
2 => "53e4db618027d69eab65f2ce"
3 => "54afbeb7abdf8e3d30bd5993"
]