如何过滤PHP Array stdClass对象

时间:2015-03-13 07:06:24

标签: php arrays json filter

我在JSON中获得的数据如下所示

$page = file_get_contents("http://giswebcenter.mwa.co.th/mwa/ashx/Proxy.ashx");
$json_output = json_decode($page);

然后我在print_r($ json_output)

时有这样的数据
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
            )

        [7] => stdClass Object
            (
                [BRANCH] => 01
                [ZONE] => 04
                [BLOCK] => 05
                [MATL] => SCP
                [LENGTH] => 19.979
            )

        [8] => stdClass Object
            (
                [BRANCH] => 01
                [ZONE] => 04
                [BLOCK] => 05
                [MATL] => ST
                [LENGTH] => 28.591
            )

        [9] => stdClass Object
            (
                [BRANCH] => 01
                [ZONE] => 04
                [BLOCK] => 07
                [MATL] => SCP
                [LENGTH] => 38.967
            )
        )
)

我想将数组中的数据过滤为ZONE ='03'
我已经用array_filter()尝试了这段代码,但注意到了。

function filterZone($obj)
{
    return $obj['data']->BRANCH == "01";
}
$BRANCH = array_filter($json_output, 'filterZone');
print_r($BRANCH);

有人可以帮忙或建议我这样做吗?
谢谢。

1 个答案:

答案 0 :(得分:0)

非常简单。您正在尝试使用array_filter实际上不是数组(或者至少是您尝试迭代的数组)。

你想要运行更像这样的东西:

function filterZone($obj)
{
    return $obj['ZONE'] == '03';
}
$BRANCH = array_filter($json_output->data, 'filterZone');
print_r($BRANCH);