You can do something like:
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]'); $greens = array_filter($o, function($item) { if ($item->color == 'green') { return true; } return false; });
Or if you want to create something really common, you can do something like the following:
function filterArray($array, $type, $value) { $result = array(); foreach($array as $item) { if ($item->{$type} == $value) { $result[] = $item; } } return $result; } $o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]'); $greens = filterArray($o, 'color', 'green'); $yellows = filterArray($o, 'color', 'yellow');
In my second example, you can simply pass an array and tell the function what to filter (for example, color or some other property of the future) based on what the value is.
Please note that I did not make any mistakes, checking if the properties really exist
source share