如何在这种类型的多维数组上使用foreach循环进行分析?

时间:2013-12-07 12:55:06

标签: php arrays multidimensional-array

我试图通过使用print_r($link_array);

从这个多维数组中获取值。

该数组实际上来自google rss api。

 Array ( [0] => Array ( [title] => World Cup draw -- group-by-group analysis [link] =>          http://www.dawn.com/news/1061096/world-cup-draw-group-by-group-analysis [author] => [publishedDate] => Sat, 07 Dec 2013 02:31:51 -0800 [contentSnippet] => GROUP A: Brazil, Croatia, Mexico, Cameroon - Having hit form in spectacular style earlier this year by winning the ... [content] =>asdfasdf
[categories] => Array ( [0] => Sport/Football ) ) [1] => Array ( [mediaGroups] => Array ( [0] => Array ( [contents] => Array ( [0] => Array ( [url] => http://i.dawn.com/primary/2013/12/52a2f7a584e2a.jpg [type] => image/jpeg [medium] => image [title] => Brazil's head coach Luiz Felipe Scolari. -Photo by AP [thumbnails] => Array ( [0] => Array ( [url] => http://i.dawn.com/primary/2013/12/52a2f7a584e2a.jpg ) ) ) ) ) )

我尝试了以下三种方式

echo $link_array[0];
   echo $link_array[title];

          foreach($link_array as $key=>$value){

           echo $key;

    }

请求帮助。

3 个答案:

答案 0 :(得分:0)

您的猜测大多是正确的,但是您要打印其密钥,只需尝试访问value['title']即可获得标题:

foreach($link_array as $key=>$value){
       echo $value['title'];
}

答案 1 :(得分:0)

您需要先将数组分配给变量。

$link_array = Array ( [0] => Array ( [title] => World Cup draw -- group-by-group analysis [link] =>          http://www.dawn.com/news/1061096/world-cup-draw-group-by-group-analysis [author] => [publishedDate] => Sat, 07 Dec 2013 02:31:51 -0800 [contentSnippet] => GROUP A: Brazil, Croatia, Mexico, Cameroon - Having hit form in spectacular style earlier this year by winning the ... [content] =>asdfasdf
[categories] => Array ( [0] => Sport/Football ) ) [1] => Array ( [mediaGroups] => Array ( [0] => Array ( [contents] => Array ( [0] => Array ( [url] => http://i.dawn.com/primary/2013/12/52a2f7a584e2a.jpg [type] => image/jpeg [medium] => image [title] => Brazil's head coach Luiz Felipe Scolari. -Photo by AP [thumbnails] => Array ( [0] => Array ( [url] => http://i.dawn.com/primary/2013/12/52a2f7a584e2a.jpg ) ) ) ) ) )

然后你可以像你做的那样兴奋地做

foreach ($link_array as $key=>$value):
    echo $key . " - " . $value;
endforeach;

但这不会在数组中显示您的内部数组。为此,如果is_array($link_array[$key]))

,您需要为foreach中的每个内容执行a
foreach ($link_array as $key=>$value):
    $new = $link_array[$key];
    if (is_array($new)):
        foreach ($new as $key1=>$value1):
            echo $key1 . " - " . $value1;
        endforeach;
    else: 
        echo $key . " - " . $value;
    endif;
endforeach;

您可以根据需要调整多个级别并更改回声。

答案 2 :(得分:0)

您也可以在函数中调用函数:

// call it
loopfor($link_array);
function loopfor ($DATA) {
    foreach ($DATA as $key=>$value):
        if (is_array($DATA[$key])):
            loopfor($DATA[$key]);
        else:
            echo $key . " - " . $value;
        endif;
    endforeach;
}