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.

2
  • array_multisort() but it's tricky. Commented Jun 18, 2013 at 4:49
  • @Steve can you show an example? Commented Jun 18, 2013 at 4:51

4 Answers 4

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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'].
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.

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.