简体   繁体   中英

PHP: Getting the array key by value entry.

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 ?

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.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM