Loop through Multi-Dimensional Array and Print
I have an array that I would like to pull certain information from and output it using php/html (i.e. game, id, rating). I have the basics down, although I only get the in开发者_开发技巧formation from the first array in the output. I know that looping is what I need to do, although I'm not exactly sure how to return more than one record at a time. Some of the information that is in one array may not be in the other, as you can see there is no [info] in the first one.
Here's my code:
<?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]);
?>
This is the output:
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. ) ) ) ) )
Depending on what you want to do, you can either do a nested for loop or if you have n number of dimensions, you can recursively call your function until the result is no longer an array. Something like this:
function printNode($node) {
foreach ($node as $nodeKey => $nodeValue) {
if (is_array($nodeValue)) {
printNode($nodeValue);
} else {
print $nodeValue;
}
}
}
If I understand your question correctly, all you need is a foreach
loop and it has nothing to do with multi-dimensionality.
精彩评论