laravel 从PHP关联数组中只获取特定值

xqkwcwgp  于 2022-11-18  发布在  PHP
关注(0)|答案(2)|浏览(189)

我从Eloquent查询中得到一个Laravel集合,并使用toArray()方法将其转换为数组。

Array ( [0] => Array ( [id] => 1 [details] => routes [level] => beginner [created_at] => 2022-11-16T11:09:48.000000Z [updated_at] => 2022-11-09T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 1 ) ) [1] => Array ( [id] => 2 [details] => router 2 [level] => beginner [created_at] => 2022-11-09T11:09:48.000000Z [updated_at] => 2022-11-18T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 2 ) ) [2] => Array ( [id] => 3 [details] => route [level] => route 3 [created_at] => 2022-11-15T09:05:46.000000Z [updated_at] => 2022-11-17T09:05:46.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 3 ) ) ) 1

我只需要pivot索引中milestone_id的值。
我尝试了不同的PHP方法和表示法来访问这些值,但都没有成功。

mbskvtky

mbskvtky1#

你可以用pluck

$milestoneIds = $collection->pluck('pivot.milestone_id')->toArray();
aurhwmvo

aurhwmvo2#

您可以通过数组执行foreacharray_map

$milestone_ids = array_map(function($data){
    return $data['pivot']['milestone_id'];
}, $pivot);

另一种方法是使用循环遍历数组中的每个数据集,获取要查找的值并将其放入另一个数组中。
https://www.mycompiler.io/view/7jWliNt2Vo0

相关问题