Home >Backend Development >PHP Problem >How to understand foreach traversing a two-dimensional array in php
php
It is often necessary to use the traversal of two-dimensional array
. Many people understand the traversal of one-dimensional array
, but for the traversal of two-dimensional array The understanding of traversal means there is nothing you can do. This article will take you to take a look at it.
First of all, if you want to understand the traversal of a two-dimensional array, you must first understand the principle of traversal of a one-dimensional array. Without further ado, let’s go directly to the code.
Two ways to traverse a one-dimensional array:
1. Need to operate on the keys and values of the array
<?php $arr=array('a'=>'php','c'=>'.cn'); foreach($arr as $key=>$value){ echo $key.'=>'.$value."<br>"; }
输出:a=>php c=>.cn
2. Need to operate on the keys and values of the array Operation
<?php $arr2=array('d'=>'ok','b'=>'oya'); foreach($arr2 as $value){ echo $value."<br>"; }
输出: ok oya
The traversal of a one-dimensional array is actually the internal pointer of foreach constantly pointing to the next key-value pair. If the pointer is empty, it is restored to the original pointer. Every time you point to a key-value pair, you can operate on the key-value pair inside foreach.
Then let’s take a look at the traversal of the two-dimensional array:
<?php $arr3=[[3,0,9],[7,8,3],[1,8,2]]; foreach($arr3 as $key=>$value){ foreach($value as $k=>$v){ echo '这是二维数组中索引为:'.$key.'的一维数组的第'.$k.'个,值为:'.$v.'<br>'; } echo "<br>"; } ?>
输出: 这是二维数组中索引为:0的一维数组的第0个,值为:3 这是二维数组中索引为:0的一维数组的第1个,值为:0 这是二维数组中索引为:0的一维数组的第2个,值为:9 这是二维数组中索引为:1的一维数组的第0个,值为:7 这是二维数组中索引为:1的一维数组的第1个,值为:8 这是二维数组中索引为:1的一维数组的第2个,值为:3 这是二维数组中索引为:2的一维数组的第0个,值为:1 这是二维数组中索引为:2的一维数组的第1个,值为:8 这是二维数组中索引为:2的一维数组的第2个,值为:2
In fact, the traversal of the two-dimensional array is to treat the array inside the two-dimensional array as a Variable, use foreach() again to traverse the array we treat as a variable.
Recommended: 《2021 PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of How to understand foreach traversing a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!