PHP Loop Through Multidimensional Array
Description
Multidimensional arrays are basically arrays nested inside other arrays, we can loop through multidimensional arrays using nested loops!
Syntax
We can use the following nested foreach statements to loop through multidimensional array.
foreach ( $myBooks as $book ) { //from w ww.j av a2 s .c o m
foreach ( $book as $key => $value ) {
}
}
Example
The following example uses two nested foreach loops to loop through the $myBooks array.
<?php /* w w w .j a v a 2 s .co m*/
$myBooks = array(
array(
"title" => "Learn PHP from java2s.com",
"author" => "java2s.com",
"pubYear" => 2000
),
array(
"title" => "Learn Java from java2s.com",
"author" => "JavaAuthor",
"pubYear" => 2001
),
array(
"title" => "Learn HTML from java2s.com",
"author" => "HTMLAuthor",
"pubYear" => 2002
),
array(
"title" => "Learn CSS from java2s.com",
"author" => "CSSAuthor",
"pubYear" => 2003
),
);
$bookNum = 0;
foreach ( $myBooks as $book ) {
$bookNum++;
echo "Book #$bookNum:";
foreach ( $book as $key => $value ) {
echo "$key :$value \n";
}
}
?>
The code above generates the following result.