1

Good day. I have a multidimensional array

Array ( [0] => stdClass Object ( [id] => 1 [title] => "Title1")
        [1] => stdClass Object ( [id] => 3 [title] => "Title2")
        [2] => stdClass Object ( [id] => 4 [title] => "Title3")
      )

How can I get the number of the array by value from the array.

For example: how to get [2] having [id] => 4 or 0 on [id] => 1 ?

3 Answers 3

1

Naive search:

$id = 4;
foreach($array as $k=>$i) {
   if ($i->id == $id)
     break;
}

echo "Key: {$k}";

Note that this solution may be faster than the other answers as it breaks as soon as it finds it.

Sign up to request clarification or add additional context in comments.

1 Comment

"Vote Up requires 15 reputation". I have only 3.
1
function GetKey($array, $value) {
    foreach($array as $key => $object) {
        if($object->id == $value) return $key;
    }
}

$key = GetKey($array, 4);

This function runs all over the objects, if the id matches the one you supplied, then it returns the key.

Comments

0

You can create a new array to map ids to indexes, by iterating the original array:

$map = [];
foreach($array as $key=>$value)
    $map[$value->id]=$key;

echo 'object with id 4 is at index ' . $map[4];
echo 'object with id 1 is at index ' . $map[1];

If you will want to look up more than one id, this is more efficient than iterating the original array each time.

If you want to access other data from the ojects, you can store them in the new array, insead of storing the index:

$objects = [];
foreach($array as $obj)
    $objects[$obj->id]=$obj;

echo 'object with id 4 has the following title: ' . $obj[4]->title;
echo 'object with id 1 has the following title: ' . $obj[1]->title;

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.