PHP foreach with Nested Array: A Comprehensive Guide
In PHP, navigating through nested arrays can be a common challenge. This discussion focuses on a specific scenario where you aim to display a subset of a nested array, specifically the values within the second nested array.
Using foreach with Nested Arrays
To handle nested arrays with foreach, you can employ the following approach:
Example:
$tmpArray = [
[
"one",
[1, 2, 3]
],
[
"two",
[4, 5, 6]
],
[
"three",
[7, 8, 9]
]
];
foreach ($tmpArray as $innerArray) {
if (is_array($innerArray)) {
foreach ($innerArray as $value) {
echo $value;
}
} else {
echo $innerArray;
}
}
Recursive Solution for Unknown Depth
If you are unsure of the depth of nesting in your array, you can employ a recursive solution:
function displayArrayRecursively($arr, $indent = '') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
displayArrayRecursively($value, $indent . '--');
} else {
echo "$indent $value \n";
}
}
}
}
Specific Case: Displaying Third Level Only
In your specific case, you only want to display the values of the third level nested array:
foreach ($tmpArray as $inner) {
if (is_array($inner)) {
foreach ($inner[1] as $value) {
echo "$value \n";
}
}
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3