PHP Two Dimensional Incidence Array Traversal Way of Example Explanation

  • 2021-08-10 07:27:13
  • OfStack

Using foreach loop to traverse 2-D index array is relatively faster and more efficient. foreach loop is specially used to loop array in PHP.

The example is also relatively simple, so practice more and think clearly about the running logic of the program.


<?php
 $arr = array(// Defining an outer array 
 " Head of Beijing "=>array(1,' Gao Mou ','A Company ',' Beijing ','(010)987654321','gm@Linux.com'),// Subarray 1
 " Head of Shanghai "=>array(2,' Luo Mou ','B Company ',' Shanghai ','(021)123456789','lm@apache.com'),// Subarray 2
 " Head of Tianjin "=>array(3,' Feng Mou ','C Company ',' Tianjin ','(022)24680246','fm@mysql.com'), // Subarray 3
 " Head of Chongqing "=>array(4,' Shumou ','D Company ',' Chongqing ','(023)13579135','sm@php.com')  // Subarray 4
 );
 
 foreach($arr as $key=>$arr_item){
  echo $key; // Fetch the key of the array 
  echo "<pre>";
   print_r($arr_item); //$arr_item Is the subarray 
  echo "</pre>";
  foreach($arr_item as $value){
   echo $value."===";  // The value of the array 
  }
 }
?>

Summary:

1. The for loop may not be used when traversing 2-dimensional associative arrays.

2. $key, take out the key of $arr array

3. $arr_item is the subarray (subarray 1, subarray 2...)


Related articles: