任意键上的 Laravel `array_pluck`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33210882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:32:12  来源:igfitidea点击:

Laravel `array_pluck` on any key

phplaravel

提问by David Rodrigues

Is possible use something like array_pluck($array, 'users.*.id')?

可以使用类似的东西array_pluck($array, 'users.*.id')吗?

Imagine that I have:

想象一下,我有:

$array = [
    'users' => [
        [ 'id' => 1 ],
        [ 'id' => 2 ],
        [ 'id' => 3 ],
    ]
];

And I want get [1, 2, 3].

我想要得到[1, 2, 3]

I tried something like: users.*.id, users.idand users..id, but nothing worked.

我尝试了类似的东西:users.*.id, users.idand users..id,但没有任何效果。

采纳答案by Ben Swinburne

Use array_pluck($array['users'], 'id')

array_pluck($array['users'], 'id')

The function only supports a single dimensional array. It will search for keys in the array which match the second parameter; which in your case is 'id'. You'll note that the array you're searching in your examples only has a key named usersand none with the name id.

该函数仅支持一维数组。它将在数组中搜索与第二个参数匹配的键;在你的情况下是'id'。您会注意到,您在示例中搜索的数组只有一个名为 的键,users而没有名为name的键id

Using $array['users']means pluck looks through that array and subsequently finds keys named idon each element.

使用$array['users']mean pluck 查找该数组,然后找到id每个元素上命名的键。

回答by Basit

You can use Laravel collectionsto achieve something like this.

您可以使用Laravel 集合来实现类似的功能。

$data = collect($array['users']);
$ids = $data->pluck('id');
return $ids;

回答by Okipa

you should use https://laravel.com/docs/5.7/helpers#method-array-pluck.
Don't recreate helpers that already exist ;)

你应该使用https://laravel.com/docs/5.7/helpers#method-array-pluck
不要重新创建已经存在的助手;)