【问题标题】:PHP, stdClass, select elements contains specifed elementPHP,stdClass,选择元素包含指定元素
【发布时间】:2015-02-10 22:31:50
【问题描述】:

我有一个这样的 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”来写,但我希望有另一种方式。谢谢

【问题讨论】:

  • 您从哪里/如何获取数据?
  • @Pinoniq 是 VK.com 的开放 API

标签: php arrays foreach stdclass


【解决方案1】:

您的外部对象实际上是一个变相的数组。您可以通过类型转换将其转换为真实数组:

$arr = (array)$obj;

那么你可以使用:

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

得到一个只包含你需要的对象的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2012-12-13
    • 2018-06-15
    • 2023-03-18
    相关资源
    最近更新 更多