i have an array full of objects , in each object there is properties i wanna collect a specific property in all the object that i have and assign them to a variable.
this is the array
[
{
"id": 23,
"user_id": 2,
"friend_id": 2,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
},
{
"id": 31,
"user_id": 2,
"friend_id": 1,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
},
{
"id": 32,
"user_id": 2,
"friend_id": 4,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
}
]
i wanna get the value of friend_id
whats the best practices to do so? thanks.
</div>
You can use array map. What this will do is assign all the friend id's into a new array. I'm passing an anonymous function that returns just the friend id out of the object. For more info on array_map
: http://php.net/manual/en/function.array-map.php
<?php
$json = '[
{
"id": 23,
"user_id": 2,
"friend_id": 2,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
},
{
"id": 31,
"user_id": 2,
"friend_id": 1,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
},
{
"id": 32,
"user_id": 2,
"friend_id": 4,
"created_at": "2018-05-23 21:00:07",
"updated_at": "2018-05-23 21:00:07"
}
]';
$jsonObject = json_decode($json);
$newArray = array_map(function($a) {
return $a->friend_id;
}, $jsonObject);
print_r($newArray);
That looks like a json string, so you would need to decode it first:
$friends = json_decode($json_string, true);
The you can extract the ids with array column as suggested in comments, or a foreach loop if you are using php 5.4 or below:
$friend_ids = array_column($friends, 'friend_id');
//OR
$friend_ids=array();
foreach($friends as $friend)
$friend_ids[] = $friend['friend_id'];