2

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Trindaz
  • 17,029
  • 21
  • 82
  • 111

4 Answers4

4

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));
  • 2
    Quick note for any other PHP novices: This solution works great for a decoded json *object*, but when implementing it for an array of *associative arrays*, make sure to change the $el->id reference to $el['id']. – Trindaz Jun 18 '13 at 05:38
1
array_map(function($arr){return $arr[0];}, $array);

This should do it.

Edit As noted by Jonathon Hibbard, you could pass array element by reference, this way you do not to assign result of the function and just use changed old array. The code should then be modified appropriately.

Cthulhu
  • 1,379
  • 1
  • 13
  • 25
0

First decode json by json_decode. You will get an array. Then follow this link to remove an index from an associative array. Then again decode it. It should work.

Community
  • 1
  • 1
Amar Banerjee
  • 4,992
  • 5
  • 34
  • 51
0

do something like:

$array = json_decode($some_json_string, true);
array_walk($array, function($value, $key) use(&$array) {
  if($key == "name") {
    unset($array[$key]);
  }
});

Edit: Cthulhu's answer won't get ya there without re-assigning it. Could use it as a reference though (equal to the walk. though if you want to use the map, its a bit better not to reallocate with a brand new array copy and just pass it by reference, then remove the key with an unset within it and move on.)

array_map(function(&$array) { unset($array['name']; }, $array);
Jonathon Hibbard
  • 1,547
  • 13
  • 20