使用PHP解析JSON - 不规则格式

时间:2016-01-13 22:04:54

标签: php json

php的新手,并试图弄清楚如何解析以看似奇怪的格式返回的API数据。以下是数据样本:

[{"campaign_id":"9000","date":"2016-01-11","totalcount":"1838","page":"1","totalpages":1,"index":1,"count":1838},{"video2.stack.com":["84254","105","0","83.71"],...,"zierfischforum.at":["1","0","0","0.00"]}]

1 个答案:

答案 0 :(得分:1)

以下是example如何将JSON解析为数组:

$json_string = '[{"campaign_id":"9000","date":"2016-01-11","totalcount":"1838","page":"1","totalpages":1,"index":1,"count":1838},{"video2.stack.com":["84254","105","0","83.71"],"zierfischforum.at":["1","0","0","0.00"]}]';

$json_array = json_decode($json_string, true); // true gets us an array

echo '<pre>';
print_r($json_array);

echo $json_array[1]['video2.stack.com'][0];

提供以下结果:

Array
(
    [0] => Array
        (
            [campaign_id] => 9000
            [date] => 2016-01-11
            [totalcount] => 1838
            [page] => 1
            [totalpages] => 1
            [index] => 1
            [count] => 1838
        )

    [1] => Array
        (
            [video2.stack.com] => Array
                (
                    [0] => 84254
                    [1] => 105
                    [2] => 0
                    [3] => 83.71
                )

            [zierfischforum.at] => Array
                (
                    [0] => 1
                    [1] => 0
                    [2] => 0
                    [3] => 0.00
                )

        )

)
84254

首先我们输出整个数组。根据数据,我们可以为video2.stack.com的一个数组部分挑出一个值。遍历相对容易,您应该能够提取所需的任何信息。您甚至可以为JSON构建递归搜索功能。

注意:我删除了部分数据(部分,...),因为它使您的JSON无效。