PHP foreach with Nested Array
Question: How to access a specific nested array using a foreach loop in PHP?
Consider the following nested array:
<code class="php">array( [0] => array( [0] => one [1] => array( [0] => 1 [1] => 2 [2] => 3 ) ) [1] => array( [0] => two [1] => array( [0] => 4 [1] => 5 [2] => 6 ) ) [2] => array( [0] => three [1] => array( [0] => 7 [1] => 8 [2] => 9 ) ) ) );</code>
The goal is to iterate through the values of the nested array at key 1, without using a variable comparison.
Answer: There are two approaches to achieve this:
1. Nested Loops (Fixed Depth):
This method is suitable if the depth of the nested arrays is known in advance.
<code class="php">foreach ($tmpArray as $innerArray) { if (is_array($innerArray)) { foreach ($innerArray as $value) { echo $value; } } else { echo $innerArray; } }</code>
2. Recursive Function (Unknown Depth):
This approach is used when the depth of the nested arrays is unknown. It involves a recursive function that traverses the array:
<code class="php">function displayArrayRecursively($arr, $indent='') { if ($arr) { foreach ($arr as $value) { if (is_array($value)) { displayArrayRecursively($value, $indent . '--'); } else { echo "$indent $value \n"; } } } } $tmpArray = array( array("one", array(1, 2, 3)), array("two", array(4, 5, 6)), array("three", array(7, 8, 9)) ); displayArrayRecursively($tmpArray);</code>
Specific Case:
To access only the nested array with values for the third level (key 2), use the following code:
<code class="php">foreach ($tmpArray as $inner) { if (is_array($inner)) { foreach ($inner[1] as $value) { echo "$value \n"; } } }</code>
以上是如何在 PHP 中使用 foreach 存取特定索引處的巢狀陣列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!