PHP如何检测JSON解码部分是对象还是数组

时间:2015-11-04 18:23:34

标签: php json

我有JSON:

{
    "catalogs": [
        {
            "aa" : "aa",
            "bb" : "bb"
        },
        [
            {
                "cc" : "cc",
                "dd" : "dd"
            },
            {
                "ee" : "ee",
                "ff" : "ff"
            }
        ]
    ]
}

和PHP代码:

<?php 

$catalogs = file_get_contents('test.json');
$catalogs = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $catalogs), true );

$catalogs = $catalogs['catalogs'];
foreach($catalogs as $catalog){
    echo gettype($catalog) . '<br/>';
}

输出是:

array
array

但我需要这样的东西:

object
array

1 个答案:

答案 0 :(得分:1)

将JSON解码为对象工作:

<?php 

$catalogs = file_get_contents('test.json');
$catalogs = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $catalogs) );

$catalogs = $catalogs->catalogs;
foreach($catalogs as $catalog){
    echo gettype($catalog) . '<br/>';
}

输出:

object
array