PHP, stdClass, select elements contain the given element

I have a stClass object, for example:

object(stdClass)#2 (6) { [0]=> object(stdClass)#44 (2) { ["uid"]=> int(3232) ["type"]=> string(7) "sibling" } [1]=> object(stdClass)#43 (2) { ["uid"]=> int(32323) ["type"]=> string(7) "sibling" } [2]=> object(stdClass)#42 (2) { ["uid"]=> int(3213) ["type"]=> string(10) "grandchild" } [3]=> object(stdClass)#41 (3) { ["uid"]=> int(-680411188) ["type"]=> string(6) "parent" } [4]=> object(stdClass)#40 (3) { ["uid"]=> int(-580189276) ["type"]=> string(6) "parent" } [5]=> object(stdClass)#39 (2) { ["uid"]=> int(3213) ["type"]=> string(7) "sibling" } } 

How can I get the elements with the specified value of the type element? For example, if I select "parent", I want to get the following:

 object(stdClass)#2 (6) { [3]=> object(stdClass)#41 (3) { ["uid"]=> int(-680411188) ["type"]=> string(6) "parent" } [4]=> object(stdClass)#40 (3) { ["uid"]=> int(-580189276) ["type"]=> string(6) "parent" } } 

I know how to write it using foreach "and" if ", but I hope there is another way. Thanks

0
source share
1 answer

Your external object is actually an array that is hidden. You can convert it to a real array using typecasting:

 $arr = (array)$obj; 

Then you can use:

 $filtered = array_filter( $arr, function($item) { return $item->type == 'parent'; } ); 

to get an array containing only the objects you need.

+1
source

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


All Articles