循环通过多维数组和打印

时间:2010-11-10 08:15:56

标签: php arrays multidimensional-array

我有一个数组,我想从中提取某些信息并使用php / html(即游戏,id,评级)输出。我有基础知识,虽然我只从输出中的第一个数组获取信息。我知道循环是我需要做的,虽然我不确定如何一次返回多个记录。一个阵列中的某些信息可能不在另一个阵列中,因为您可以看到第一个中没有[info]。

这是我的代码:

<?php

$review = $developer->api('/source');

    function d($d){
        echo '<pre>';
        print_r($d);
        echo '</pre>';
    }

    d($review[data][0][game]);
    d($review[data][0][game][rating]);
?>

这是输出:

Array( [data] => Array ( [0] => Array ( [id] => 2010_1110 [from] => Array ( [name] => Pebkac [id] => 11001010  ) [game] => Array ( [id] => 2112 [name] => New Game [rating] => Array ( [action] => 9 [graphics] => 10 ) ) [comments] => Array ( [data] => Array ( [0] => Array ( [id] => 2010_1111 [from] => Array ( [name] => My Friend  [id] => 10100110 ) [message] => hi there. [created_time] => 8:00 P.M. ) ) ) ) ) 

[paging] => Array ( [previous] => url1 [next] => url2 ))

Array( [data] => Array ( [1] => Array ( [id] => 2010_1112 [from] => Array ( [name] => Pebkac [id] => 11001010  ) [game] => Array ( [id] => 5050 [name] => Another Game [rating] => Array ( [action] => 8 [graphics] => 8 ) ) [info] => [created_time] => 8:59 P.M. [owns] => Array ( [data] => Array ( [0] => Array ( [id] => 20100112   [name] => Friend Two ) ) ) [comments] => Array ( [data] => Array ( [0] => Array ( [id] => 2010_1113 [from] => Array ( [name] => My Friend  [id] => 10100110 ) [message] => hi there. [created_time] => 9:00 P.M. ) ) ) ) ) 

2 个答案:

答案 0 :(得分:4)

根据您的目的,您可以执行嵌套for循环,或者如果您有n个维度,则可以递归调用函数,直到结果不再是数组。像这样:

function printNode($node) {
    foreach ($node as $nodeKey => $nodeValue) {
        if (is_array($nodeValue)) {
            printNode($nodeValue);
        } else {
            print $nodeValue;
        }
    }
}

答案 1 :(得分:0)

如果我正确理解了您的问题,您只需要一个foreach循环,它与多维度无关。