遍历 PHP 中的嵌套数组


Iterating through nested array in PHP

我正在使用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
                )

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

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

使用:

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

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

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