Home > Software design >  Getting Only specific values from a PHP associative array
Getting Only specific values from a PHP associative array

Time:11-10

I get a Laravel collection from a Eloquent query and I converted into an array using toArray() method. The sample output is mentioned below.

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

I only need the values of milestone_ids from pivot index. As an example like this [1,2,3]

I tried different PHP methods and notations to access these values but couldn't succeed.

CodePudding user response:

You could foreach or array_map through the array

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

The other way would be to use a loop to go through each data set in the array and get the value you are looking for and drop it in another array.

https://www.mycompiler.io/view/7jWliNt2Vo0

CodePudding user response:

You can use pluck

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