Traverse array
Traverse a numerical array
Traversing all elements in an array is a common operation, and queries or other functions can be completed during the traversal process.
<1>Use the for structure to traverse the array;
Example
<?php //声明一个数组,值为1到10 $num = array(1,2,3,4,5,6,7,8,9,10); //按照索引数组的特点,下标从0开始。所以1的下标为0,10的下标为9 echo $num[0].'<br />'; echo $num[9].'<br />'; //我们可以得到数组中元素的总个数,为10 echo count($num); //遍历这个索引数组的话,我们就可以定义一个变量为$i //$i 的值为0,从0开始 //可以设定一个循环条件为:$i 在下标的(9)最大值之内循环 for($i = 0 ; $i < count($num) ; $i++){ echo $num[$i].'<br />'; } ?>
can complete the array traversal.
Starting from 0, define $i=0. Let $i increase by 1 each time it loops, but it must be less than 10, because the maximum value of the array subscript is 9.
In this way, we have learned to traverse the indexed consecutive subscript array.
<2>Use the foreach structure to traverse the array;
The for loop can traverse the index array of consecutive subscripts. However, we found that we cannot traverse associative arrays, nor can we traverse index arrays with discontinuous subscripts.
In fact, when we were learning loops, there was a Boolean loop specially used to loop arrays. The basic syntax of this loop is the basic syntax of foreach.
The syntax format is as follows:
foreach(array variable to be looped as [key variable=>] value variable){
//Structure of loop
}
Traverse associative array
<?php $data = [ 'fj' => '凤姐', 'fr' => '芙蓉', ]; foreach($data as $key => $value){ echo $key . '-------' . $value . '<br />'; } //如果我们只想读取值的话,就可以把下面的$key => 给删除掉,读取的时候,就只读取值了。做完上面的实验,你可以打开下面的代码再实验几次。 /* foreach($data as $value){ echo $value . '<br />'; } */ ?>
Traverse index array
We can traverse continuous through foreach The index array, as in the following example:
<?php $data = array( 0 => '中国', 100 => '美国', 20 => '韩国', 300 => '德国', ); //待会儿可以自己做做实验,循环遍历一下下面的这个数组 //$data = array(1,2,3,4,5,6,7,8,9,10); foreach($data as $k => $v){ echo $k . '------' . $v .'<br />'; } ?>
Traverse multi-dimensional array
<?php $data = array( 0 => array( '中国' => 'china', '美国' => 'usa', '德国' => ' Germany', ), 1 => array( '湖北' => 'hubei', '河北' => 'hebei', '山东' => 'shandong', '山西' => 'sanxi', ), ); //注:我们在使用foreach循环时,第一次循环将键为0和键为1的两个数组赋值给一个变量($value)。然后,再套一个循环遍历这个$value变量,$value中的值取出来,赋值给$k和$v。 foreach($data as $value){ //第一次循环把国家的数组赋值给了$value //第二次循环把中国的省份的数组又赋值给了$value //因此,我在循环的时候把$value再遍历一次 foreach($value as $k => $v){ echo $k . '-----' . $v .'<br />'; } //为了看的更清晰,我在中间加上华丽丽的分割线方便你来分析 echo '----------分割线-----------<br />'; } ?>
Summary:
1. The first time you loop, assign the array Given $value, then use foreach to loop over $value. Give the key in the two-dimensional subarray to $k and assign the value to the variable $v.
2. The first loop exits the sub-array loop, and the subsequent code is executed to display the dividing line.
3. And so on, the same is true for the second cycle.