【问题标题】:How can I filter stdClass object如何过滤 stdClass 对象
【发布时间】:2015-05-15 12:18:10
【问题描述】:

我有下面将 JSON 放入数组的数据

stdClass Object
(
    [success] => 1
    [total] => 850
    [message] => 
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 03
                    [BLOCK] => 04
                    [MATL] => ST
                    [LENGTH] => 516.492
                )

            [1] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 03
                    [BLOCK] => 05
                    [MATL] => SCP
                    [LENGTH] => 19.177
                )

            [2] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 03
                    [BLOCK] => 05
                    [MATL] => ST
                    [LENGTH] => 519.355
                )

            [3] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 03
                    [BLOCK] => 06
                    [MATL] => SCP
                    [LENGTH] => 59.713
                )

            [4] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 03
                    [BLOCK] => 06
                    [MATL] => ST
                    [LENGTH] => 476.866
                )

            [5] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 04
                    [BLOCK] => 03
                    [MATL] => SCP
                    [LENGTH] => 64.875
                )

            [6] => stdClass Object
                (
                    [BRANCH] => 01
                    [ZONE] => 04
                    [BLOCK] => 03
                    [MATL] => ST
                    [LENGTH] => 44.888
                ) ....

我想将 Array 中的数据过滤为 ZONE = '03'。
谁能给出示例代码来做到这一点?
谢谢。

【问题讨论】:

标签: php arrays json filter


【解决方案1】:

你可以使用 array_filter http://php.net/manual/en/function.array-filter.php

$input = (object)array(
  'success'=>1,
  'total'=>850,
   'data'=>array(
    (object)array('ZONE'=>'01'),
    (object)array('ZONE'=>'04'),
    (object)array('ZONE'=>'04'),
    (object)array('ZONE'=>'04'),
    (object)array('ZONE'=>'03'),
    (object)array('ZONE'=>'02')
  )
);

$output = array_filter($input->data,function($object){
  return $object->ZONE == '04';
});

print_r($output);

array_filter 的工作原理是测试数组中的每个项目并返回 TRUE 或 FALSE。

【讨论】:

    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2011-08-31
    • 1970-01-01
    • 2014-03-08
    • 2013-04-23
    • 1970-01-01
    相关资源
    最近更新 更多