在PHP JSON对象中处理数据


85

来自Twitter Search API中JSON的趋势数据。

使用以下文件来抓取文件:

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

如何处理来自该对象的数据。作为数组?只需要从[name]值中提取数据即可。

JSON对象包含:

stdClass Object
(
    [trends] => Array
        (
            [0] => stdClass Object
                (
                    [name] => Vote
                    [url] => http://search.twitter.com/search?q=Vote
                )

            [1] => stdClass Object
                (
                    [name] => Halloween
                    [url] => http://search.twitter.com/search?q=Halloween
                )

            [2] => stdClass Object
                (
                    [name] => Starbucks
                    [url] => http://search.twitter.com/search?q=Starbucks
                )

            [3] => stdClass Object
                (
                    [name] => #flylady
                    [url] => http://search.twitter.com/search?q=%23flylady
                )

            [4] => stdClass Object
                (
                    [name] => #votereport
                    [url] => http://search.twitter.com/search?q=%23votereport
                )

            [5] => stdClass Object
                (
                    [name] => Election Day
                    [url] => http://search.twitter.com/search?q=%22Election+Day%22
                )

            [6] => stdClass Object
                (
                    [name] => #PubCon
                    [url] => http://search.twitter.com/search?q=%23PubCon
                )

            [7] => stdClass Object
                (
                    [name] => #defrag08
                    [url] => http://search.twitter.com/search?q=%23defrag08
                )

            [8] => stdClass Object
                (
                    [name] => Melbourne Cup
                    [url] => http://search.twitter.com/search?q=%22Melbourne+Cup%22
                )

            [9] => stdClass Object
                (
                    [name] => Cheney
                    [url] => http://search.twitter.com/search?q=Cheney
                )

        )

    [as_of] => Mon, 03 Nov 2008 21:49:36 +0000
)
php  json 

Answers:


146

你的意思是这样吗?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

是否还有其他方法可以获取名称列表而无需循环,例如$ trends [“ name”]或$ trends [] [“ name”]?
2014年

35

如果使用json_decode($string, true),将不会获得任何对象,但是会得到所有关联或数字索引的数组。更容易处理,因为PHP提供的stdObject只是具有公共属性的哑容器,无法使用您自己的功能进行扩展。

$array = json_decode($string, true);

echo $array['trends'][0]['name'];

8

就像使用您定义的对象一样使用它即可。即

$trends = $json_output->trends;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.