tags:

views:

50

answers:

2

Is there a way to get a JSON object out of a JSON object array depending on its value?

What I've got:

$users = [{"id":1, "name":"Some Name"},
          {"id":2, "name":"Another Name"},
          {"id":3, "name":"Third Name"}];

And what I want is to pull out the user depending on the id. So I might have an AJAX call that sends in user=2. What I want is to pull the user with an id of 2 from the JSON array.

I'm wondering if this is the best way to do it or not. I have full access to set up the JSON array another way, if that would make it easier.

A: 

If you want ease of retrieving the user on the client:

jsonData = 
{ 
  "selectedId": 2,
  "users":
  {
    "Id1": {"id":1, "name":"Some Name"},
    "Id2": {"id":2, "name":"Another Name"},
    "Id3": {"id":3, "name":"Third Name"},
    "Id100": {"id":100, "name":"Some Name"}
  }
}

and on the client...

var selectedId = data.selectedId;
var user = data.users["Id" + selectedId];

You may not even need the "Id" prefix here. My concern about the array-based approach is that you can never guarantee that IDs are sequential. This approach, which uses object properties, is not bound by that kind of limitation.

David Andres
+1  A: 

If you're performing that operation/search many times on the same array you might consider using the id as key of a hashtable/array.

$json = '[{"id":1, "name":"Some Name"},
          {"id":4, "name":"Another Name"},
          {"id":9, "name":"Third Name"}]';

$users = array();
foreach(json_decode($json, true) as $u) {
  $users[$u['id']] = $u;
}

echo $users[9]['name'];
VolkerK