The array looks like:

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

And I have a integer variable called $v.

How could I select a array entry that has a object where the 'ID' property has the $v value ?

share|improve this question

1 Answer

up vote 19 down vote accepted

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

For the former, something like this

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes

share|improve this answer
setting $item to null is not needed. – dAm2K Sep 30 '12 at 20:06
@dAm2K Not sure what you mean. I'm not setting $item to null anywhere – Phil Oct 1 '12 at 0:17
check your first line of code. – dAm2K Oct 1 '12 at 14:22
1  
Oops, there it is :) That is in case the sought item is not in the array. Alternatively, you could use isset($item) but I prefer initialising variables properly – Phil Oct 1 '12 at 23:41

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.