【问题标题】:Iterating through nested array in PHP遍历PHP中的嵌套数组
【发布时间】:2016-02-23 06:20:31
【问题描述】:

我正在使用 Twitter Rest API 来收集有关热门话题的信息。 API 返回 JSON,我正在尝试解析数据。

这是我的相关代码(我不包括我的钥匙等):

$twitter = new TwitterAPIExchange($settings); 
$string = json_decode($twitter->setGetfield($getfield)
     ->buildOauth($url, $requestMethod)
     ->performRequest(), true);

if($string["errors"][0]["message"] != "") 
    {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>"
    .$string[errors][0]["message"]."</em></p>";exit();}     

foreach($string as $items)
    {
        echo "Name: ". $items['name']."<br />";
        echo "Volume: ". $items['tweet_volume']."<br /><hr />";
    }

它返回的是一个嵌套数组,看起来像这样:

Array
(
[0] => Array
    (
        [trends] => Array
        (
            [0] => Array
                (
                    [name] => #NationalMargaritaDay
                    [url] => http://twitter.com/search?q=%23NationalMargaritaDay
                    [promoted_content] => 
                    [query] => %23NationalMargaritaDay
                    [tweet_volume] => 49400
                )
            [1] => Array
                (
                    [name] => #WORKvideo
                    [url] => http://twitter.com/search?q=%23WORKvideo
                    [promoted_content] => 
                    [query] => %23WORKvideo
                    [tweet_volume] => 103959
                )

...等等(我不会列出整个数组)。

我需要做的是能够遍历 [trends] 数组而不是父数组。如何修改我的 foreach 循环来做到这一点?或者,我可以在 for each 之前放置一两步,以便遍历内部数组吗?我需要能够从每个项目中提取[name][twitter_volume]

【问题讨论】:

  • 这是$string的值?

标签: php arrays json


【解决方案1】:

用途:

foreach($string[0]['trends'] as $items) {
    ...
}

或者如果$strings 的顶层有多个元素,则需要嵌套循环:

foreach ($string as $el) {
    foreach ($el['trends'] as $items) {
        ...
    }
}

【讨论】:

  • 由于 API 查询末尾的一些其他内容,我不得不使用嵌套循环选项。对于访问 Twitter API 以获取趋势数据的人们来说,这是一个很好的提示!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
相关资源
最近更新 更多