How can I get a key object from a value? Is there something like array_search for objects?

I have a class like:

stdClass Object ( [id] => 1 [items] => stdClass Object ( [0] => 123 [1] => 234 [2] => 345 [3] => 456 ) ) ) 

Call the above $foo object.

Say $v = 234 . Given $foo and $v , how can I return the "key" 1 ?

If $foo->items was an array, I would just do $key = array_search($v,$foo->items); . But this does not work in the object.

How can I find the key for $v without scrolling an object in some foreach ?

+4
source share
3 answers

Use get_object_vars and do a search on the returned array.

Link : http://php.net/manual/en/function.get-object-vars.php

Here is an example of how to look for 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

+5
source

As you showed in your example, you are dealing with stdClass objects. They are very similar to arrays and with PHP you can easily convert between the two with what is called casting:

 $object = $foo->items; $key = array_search($v, (array)$object); ^^^^^^^--- cast to array 

As shown in this small example (I just used the $object variable to make the translation more visible, you can usually write it as single-line), casting from object to array allows you to use the well-known function ( array_search ) on the object.

Since arrays and stdClass objects in PHP are so similar, this works both ways:

 $array = ['property' => 'value']; $object = (object)$array; echo $object->property; # value 

This also works with other types in PHP, so there is probably something to read beyond your specific problem: Juggling & shy; Docs , but be careful that in PHP this has many special rules. But between the array and the objects, it is pretty straightforward.

+2
source

$key = array_search($v, get_object_vars($foo->items));

edit: try this

+1
source

Source: https://habr.com/ru/post/1435359/


All Articles