Walking through a multidimensional array
You can walk through a multidimensional array by using foreach statements (described in the section “Walking through an Array,” earlier in this chapter). Because a two-dimensional array, such as $foodPrices, contains two arrays, it takes two foreach statements to walk through it. One foreach statement is inside the other foreach statement. (Putting statements inside other statements is called nesting.)
The following statements echo the values from the multidimensional array:
foreach ( $foodPrices as $category ) {
foreach ( $category as $food => $price ) {
$f_price = sprintf(“%01.2f”, $price); echo “$food: \$$f_price \n”;
} }
The output is the following:
onion: $0.50 potato: $1.00 apple: $2.50 orange: $2.00 bacon: $3.50 ham: $5.00
Here is how PHP interprets these foreach statements:
2. The first key/value pair in the $category array is retrieved. The key is stored in $food, and the value is stored in $price.
3. The value in $price is formatted into the correct format for money.
4. One row for the product and its price is echoed.
5. The next key/value pair in the $category array is reached.
6. The price is formatted, and the next row for the food and its price is echoed.
7. Because there are no more key/value pairs in $category, the inner foreach statement ends.
8. The next key/value pair in the outer foreach statement is reached. The next value is put in $category, which is an array.
9. The procedure in Steps 1 through 8 is repeated until the last key/value pair in the last $category array is reached. The inner foreach statement ends. The outer foreach statement ends.
In other words, the outer foreach starts with the first key/value pair in the array. The key is vegetable, and the value of this pair is an array that is put into the variable $category. The inner foreach then walks through the array in $category. When it reaches the last key/value pair in $category, it ends. The script is then back in the outer loop, which goes on to the second key/value pair . . . and so on until the outer foreach reaches the end of the array.

0 comments:
Post a Comment