$v1){foreach($v1 as $k2=>$v2){foreach($v2 as $k3=>$v3){...}}}". Each time the foreach statement loops, the pointer inside the array will move forward one step until it traverses to the end of the array, stops traversing and exits the loop."/> $v1){foreach($v1 as $k2=>$v2){foreach($v2 as $k3=>$v3){...}}}". Each time the foreach statement loops, the pointer inside the array will move forward one step until it traverses to the end of the array, stops traversing and exits the loop.">
Home > Article > Backend Development > Can php foreach traverse a three-dimensional array?
can be traversed. In PHP, you can traverse a three-dimensional array by nesting three levels of foreach statements. The syntax is "foreach($array as $k1=>$v1){foreach($v1 as $k2=>$v2){foreach( $v2 as $k3=>$v3){...}}}". Each time the foreach statement loops, the pointer inside the array will move forward one step until it traverses to the end of the array, stops traversing and exits the loop.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
The foreach statement can traverse a three-dimensional array.
In PHP, you can traverse a three-dimensional array by nesting three levels of foreach statements.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $array = array( '安徽' => array( '合肥'=>array('蜀山区','长丰县','肥东'), '宿州'=>array('墉桥区','灵璧县','泗县') ) ); var_dump($array); foreach($array as $k1=>$v1){ echo "省名:".$k1."<br>"; foreach($v1 as $k2=>$v2){ echo "<br>市名:".$k2."<br><br>"; foreach($v2 as $k3=>$v3){ echo "区名:".$v3."<br>"; } } } ?>
Explanation:
foreach is a statement specially designed for traversing arrays. The commonly used methods when traversing arrays provide great convenience in traversing arrays; after PHP5, objects can also be traversed (foreach can only be applied to arrays and objects).
The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.
When the foreach statement loops, the pointer inside the array will move forward one step, so that the next array element will be obtained in the next loop until the end of the array is traversed, the traversal stops and the loop exits.
Two syntaxes for foreach to traverse arrays
Grammar format 1:
foreach ($array as $value){ 语句块; }
Traverse the given $array array, Assign the value of the current array to $value in each loop.
Syntax format 2:
foreach ($array as $key => $value){ 语句块; }
Traverse the given $array array, and assign the value of the current array to $value, the key name is assigned to $key.
Recommended learning: "PHP Video Tutorial", "PHP ARRAY"
The above is the detailed content of Can php foreach traverse a three-dimensional array?. For more information, please follow other related articles on the PHP Chinese website!