PHP foreach with Nested Array?
If you know the number of levels in nested arrays you can simply do nested loops. Like so:
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
if you do not know the depth of array you need to use recursion. See example below:
// Multi-dementional Source Array
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(
7,
8,
array("four", 9, 10)
))
);
// Output array
displayArrayRecursively($tmpArray);
/**
* Recursive function to display members of array with indentation
*
* @param array $arr Array to process
* @param string $indent indentation string
*/
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
//
displayArrayRecursively($value, $indent . '--');
} else {
// Output
echo "$indent $value \n";
}
}
}
}
The code below with display only nested array with values for your specific case (3rd level only)
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(7, 8, 9))
);
// Scan through outer loop
foreach ($tmpArray as $inner) {
// Check type
if (is_array($inner)) {
// Scan through inner loop
foreach ($inner[1] as $value) {
echo "$value \n";
}
}
}
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}