I have a JSON array of data that I am trying to extract particular value/keys(?) from, and would like to add them into a new array.
The array looks like this:
{ "total':2000, "achievements":[ { "id":6, "achievement":{}, "criteria":{ "id":2050, "is_completed":false }, "completed_timestamp":1224053510000 }, { "id":8, "achievement":{}, "criteria":{ "id":1289, "is_completed":true }, "completed_timestamp":0000000 } ] }
I want to search for true in the is_completed, and then add the id from that array into a new array.
Basically, find the id’s of all the key/array (sorry unsure of terminology) where is_completed is true.
I’ve tried something simple like finding trying to find the key of an ID, but struggling to get that to work. And also seen some of the multi-level for loop examples but can’t get them to work for my data. Example:
$key = array_search('1289', array_column($array, 'id'));
Advertisement
Answer
As pointed out in the comments, you could combine array_filter
(to filter completed events) and array_column
(to extract their IDs).
$completedAchievements = array_filter( $array->achievements, static function (stdClass $achievement): bool { return $achievement->criteria->is_completed === true; } ); $completedAchievementsIds = array_column($completedAchievements, 'id'); print_r($completedAchievementsIds); // Array([0] => 8)
Note: the code above supposes your JSON was decoded as an object. If it was decoded as an array, just replace ->
syntax with the corresponding array index access.