我有一个像这样的stClass对象:
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"
}
}
如何获取元素类型指定值的元素?例如,如果我选择"父",我想得到这个:
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"
}
}
我知道,如何用"foreach"和"if"来写它,但我希望还有另一种方法。谢谢
你的外部对象实际上是一个伪装的数组。您可以通过类型转换将其转换为实数组:
$arr = (array)$obj;
然后,您可以使用:
$filtered = array_filter(
$arr,
function($item) {
return $item->type == 'parent';
}
);
以获取仅包含所需对象的数组。