Hi everyone -
I'm having some problems with the way PHP handles nested arrays when using foreach.
Here's my array:
Array
(
[FOOD] => Array
(
[FRUIT] => Array
(
[0] => Array
(
[NAME] => Array
(
[VALUE] => Orange
)
[ATTRIBUTES] => Array
(
[0] => Array
(
[COLOR] => Array
(
[VALUE] => Orange
)
[SHAPE] => Array
(
[VALUE] => Round
)
)
)
)
[1] => Array
(
[NAME] => Array
(
[VALUE] => Apple
)
[ATTRIBUTES] => Array
(
[0] => Array
(
[COLOR] => Array
(
[VALUE] => Red
)
[SHAPE] => Array
(
[VALUE] => Round
)
)
[1] => Array
(
[COLOR] => Array
(
[VALUE] => Green
)
[SHAPE] => Array
(
[VALUE] => Semi-Round
)
)
)
)
)
)
)
The problem occurs when you you're trying to use a foreach to get the ATTRIBUTES out of each fruit:
//Let's say $food is the above array
foreach($food['FOOD']['FRUIT'] as $fruit){
//Now we can step through each fruit
foreach ($fruit['ATTRIBUTES'] as $attrib){
//Now we try to step through each ATTRIBUTE of a fruit, but
//we have a problem (see below)
print($attrib['COLOR']['VALUE']." ");
print($attrib['SHAPE']['VALUE']." ");
//To view this problem we can use this:
print("<pre>");
print_r($attrib);
print("</pre>");
}
}
The Apples array will print correctly, you should see:
Red Round Green Semi-Round
Because PHP correct notices that ATTRIBUTES is an array of arrays and points $attrib to Array[0] in ATTRIBUTES.
The Oranges array will give an error ... because PHP looks at the 1 dimensional ATTRIBUTES array, and then steps into it (I have no idea why, but in my tests this is what it was doing).
Here, $attrib points to ['COLOR'], which will given a error when you try to print, because ['COLOR'] does not contain ['COLOR']['VALUE'].
The print_r for $attrib will show this as well:
// $attrib Apple Arrays ... everything is where it's supposed to be:
Array
(
[COLOR] => Array
(
[VALUE] => Red
)
)
Array
(
[SHAPE] => Array
(
[VALUE] => Round
)
)
Array
(
[COLOR] => Array
(
[VALUE] => Green
)
)
Array
(
[SHAPE] => Array
(
[VALUE] => Semi-Round
)
)
//Now $attrib Orange Array ... Note that the array has been stepped into and that SHAPE and COLOR are missing
Array
(
[VALUE] => Orange
)
Array
(
[VALUE] => Round
)
In Summary: It looks like foreach will not work on a one dimensional array that contains a multidimension array, PHP attempts to step into the one dimensional array to get to the multidimension array. A multidimensioned array of multidimensioned arrays works like it is supposed to.
Has anyone run into this before ... or am I doing something wrong in my code?
-Frizzled