PHP, stdClass, select elements contains specifed element

妖精的绣舞 提交于 2020-01-07 06:50:14

问题


I have an stClass object like this:

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 elements with specified value of type element? For example, if I select "parent", I wanna get this:

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 with "foreach" and "if", but I hope that there is another way. Thanks


回答1:


Your outer object is in fact, an array in disguise. You can convert it to a real array by typecasting:

$arr = (array)$obj;

Then you can use:

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

to get an array that contains only the objects you need.



来源:https://stackoverflow.com/questions/27439824/php-stdclass-select-elements-contains-specifed-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!