Search code examples
phparraysassociative-arrayprojectionhigher-order-functions

In PHP, filter an Array of Associative Arrays


In PHP, are there any inbuilt functions to turn

[{"id":1, "name":"John"}, {"id":2, "name":"Tim"}]

into

[{"id":1}, {"id":2}]

?

I've used JSON to describe the objects above, but that's just a conceptual representation of my array of associative arrays. I don't want to have to loop manually - something short and elegant I can fit on one line would be nice.


Solution

  • One line, using array_map:

    $arr = json_decode('[{"id":1, "name":"John"}, {"id":2, "name":"Tim"}]');
    
    $new_arr = array_map(function($el){$ret=array("id"=>$el->id);return $ret;},$arr);
    
    var_dump(json_encode($new_arr));