0

I looked for an good answer but found none.

An API returns JSON like this [{id:31, name:"blue"},{id:22, name:"green"},..]

I would like to like to get the name from id $api->[where id= 2]

The only way I found was to convert this array to obj and having the id as key. Is there no better PHP way?

6
  • You can loop over the array and look for the item that has ID=2 Commented Jun 6, 2013 at 17:27
  • Will id:2 always be the 2nd position? If so you could do echo $json[1]['name'] Commented Jun 6, 2013 at 17:29
  • 1
    This might interest you ... Implementing goMongoDB-like Query expression object evaluation Commented Jun 6, 2013 at 17:32
  • No @Sean i fixed it to be more clear (am I doing the @ sean wrong?) Commented Jun 6, 2013 at 17:40
  • Good read @Baba, I'll keep this in mind when I have a bigger project. I think it would be a bit of an overkill :) Commented Jun 6, 2013 at 17:54

4 Answers 4

4

Your solution is the best way. Something like:

$results = json_decode($returned_JSON_string);

foreach($results as $result) {
    if($result->id == 2) {
        // Match!
        break;
    }
}

If you don't like the default behavior of json_decode creating an object, you can instruct it to create an array like this:

 $results = json_decode($returned_JSON_string, true);
Sign up to request clarification or add additional context in comments.

2 Comments

Is this okay? ( it works but I had to add 'id' infront of numbers to do so. I'm not that pro in PHP. ) $Obj = new stdClass(); foreach ($jobs as $item) { $key = 'id'.$item['id']; $Obj->$key = $item; } print_r($Obj->id12);
It would work if you absolutely knew that ID 12 existed, but I'd go with the safer approach and loop through as I suggested. That way, you can just execute whatever you need to do with a particular ID (2, in my example, 12 in yours) where I commented // Match!.
2

I think you can just encode your json as associative array

$arr = json_decode($json, true); //note true as second parameter because we want as associative array

and now you can call it with

echo $arr[1]['id'];

or loop in the array.

1 Comment

That only works if the id's are 1,2,3? I fixed the example to be more clear, the id's are very random it would be wonderful if I can say that id should be the key for the associative array
2

You could use array_filter:

$results = json_decode($returned_JSON_string);
$item = array_filter ($results, function($item) { $item['id'] == 2; });

1 Comment

(This is not a comment on the correctness of dave's answer or the appropriateness of it, it's a fine answer.) I always find these anonymous-function solutions hard to read. array_filter, array_map, array_reduce are all hard to figure out what is happening from a quick read. jterry's (simple) answer is much easier to read. It's probably because I'm not as comfortable with functional programming, but so be it.
1

Here is the solution for doing it in javascript

function myIndexOf(arr, o) {    
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == o) {
                return i;
            }
        }
        return -1;
    }
    var data = [{id:1, name:"blue"},{id:2, name:"green"}];

    alert(data[myIndexOf(data,2)].name);

PHP version

    function myIndexOf($arr, o) {    
            for (var i = 0; i < count(arr); i++) {
                if ($arr[i]['id'] == o) {
                    return i;
                }
            }
            return -1;
        }

$data = json_decode($json_data);
echo $data[myIndexOf($data, 2)]['name']; // will output 'green'

2 Comments

my bad, I overlooked that he wanted the solution in PHP
@AbdulHaseeb If you'll edit your answer, I can remove the down vote.

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.