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
As you have shown in your example, you're dealing with stdClass
object(s). Those are quite similar to arrays and with PHP you can easily convert between those two with something called casting :
$object = $foo->items;
$key = array_search($v, (array)$object);
^^^^^^^--- cast to array
As this little example shows (I just used the $object
variable to make the cast more visible, you normally can write it as one-liner), the cast from object to array does allow you to use the known function ( array_search
) on the object.
Because arrays and stdClass objects in PHP are so similar, this works in both directions:
$array = ['property' => 'value'];
$object = (object)$array;
echo $object->property; # value
This also works with other types in PHP, so probably apart from your concrete problem, something worth to read about: Type Juggling Docs , but take care, that in PHP this has many special rules. But between array and objects, it's pretty straight forward.
$key = array_search($v, get_object_vars($foo->items));
编辑:试试这个
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.