I have a class like so:
stdClass Object
(
[id] => 1
[items] => stdClass Object
(
[0] => 123
[1] => 234
[2] => 345
[3] => 456
)
)
)
Let's call the above object $foo
.
Let's say $v = 234
. Given $foo
and $v
, how can I return the "key" 1
?
If $foo->items
was an array I would simply do $key = array_search($v,$foo->items);
. But this doesn't work in an object.
How can I find the key for $v
without looping through the object in some foreach
?
Use get_object_vars
and search through the array returned.
Reference: http://php.net/manual/en/function.get-object-vars.php
Here's an example of how to search through the array returned for a key:
<?php
$foo = NULL;
$foo->id = 1;
$foo->items = array(123, 234, 345, 456);
$foo_array = get_object_vars($foo);
print_r($foo_array);
foreach ($foo_array as $key => $value) {
if ($value == 1) {
echo $key;
}
}
?>
Output:
Array
(
[id] => 1
[items] => Array
(
[0] => 123
[1] => 234
[2] => 345
[3] => 456
)
)
id
CodePad: http://codepad.org/in4w94nG
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With