如何过滤stdClass对象

时间:2015-03-13 04:50:03

标签: php arrays json filter

下面有关于将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
                ) ....

我想将数据过滤为ZONE ='03'。
任何人都可以给出示例代码吗?
谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以使用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来工作,返回时的括号表示法是返回布尔值的快捷方式。