Reputation: 107
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 ?
Upvotes: 1
Views: 154
Reputation: 48131
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.
Upvotes: 1
Reputation: 20469
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;
Upvotes: 0
Reputation: 3461
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.
Upvotes: 1