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開始 //可以設定一個循環(huán)條件為:$i 在下標的(9)最大值之內循環(huán) 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 => '德國', ); //待會兒可以自己做做實驗,循環(huán)遍歷一下下面的這個數組 //$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循環(huán)時,第一次循環(huán)將鍵為0和鍵為1的兩個數組賦值給一個變量($value)。然后,再套一個循環(huán)遍歷這個$value變量,$value中的值取出來,賦值給$k和$v。 foreach($data as $value){ //第一次循環(huán)把國家的數組賦值給了$value //第二次循環(huán)把中國的省份的數組又賦值給了$value //因此,我在循環(huán)的時候把$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.