Several detailed methods of traversing two dimensional arrays in php are discussed

  • 2020-06-12 08:39:33
  • OfStack

Among PHP application, the application of two dimensional array is one of the high frequency, especially with more complex computation, basically are used for 2 d or a multidimensional array, and the enlisted through more should be a multidimensional arrays use for loop through and foreach traverse two functions, with no special requirements, is essentially in the use of foreach traversal functions, of course, we can through the two traversal functions to combined into a variety of output mode.
As usual, 1 is always in use, never remember, simple traversal output is relatively simple, here are two code snippets in PHP traversal 2 dimensional function, as follows.

Loop through using for


<?PHP 
// use for To iterate over  
$arr2=array(array(" zhang 3","20"," male "),array(" li 4","25"," male "),array(" The king 5","19"," female "),array(" zhao 6","25"," female ")); 
echo "<table border=2 bordercolor=red><tr><td> The name </td><td> age </td& gt;<td> gender </td></tr>"; 
for($i=0;$i<4;$i++){ 
echo "<tr>"; 
for($j=0;$j<3;$j++){ 
  echo "<td>"; 
  echo $arr2[$i][$j]; 
  echo "</td>"; 
} 
echo "</tr>"; 
echo "<br>"; 
} 
echo "</table>"; 
?> 

Use foreach traversal:


<?php 
$arr = array('one'=>array('name'=>' zhang 3','age'=>'23','sex'=>' male '), 
  'two'=>array('name'=>' li 4','age'=>'43','sex'=>' female '), 
  'three'=>array('name'=>' The king 5','age'=>'32','sex'=>' male '), 
  'four'=>array('name'=>' zhao 6','age'=>'12','sex'=>' female ')); 
 
foreach($arr as $k=>$val){ 
  echo $val['name'].$val['age'].$val['sex']."<br>"; 
} 
echo "<p>"; 
?> 
 
<?php 
$arr = array('one'=>array('name'=>' zhang 3','age'=>'23','sex'=>' male '), 
  'two'=>array('name'=>' li 4','age'=>'43','sex'=>' female '), 
  'three'=>array('name'=>' The king 5','age'=>'32','sex'=>' male '), 
  'four'=>array('name'=>' zhao 6','age'=>'12','sex'=>' female ')); 
foreach($arr as $key=>$value){ 
foreach($value as $key2=>$value2){ 
  echo $value2; 
} 
echo "<br>"; 
}  
?> 

We can print directly, the output of the form file, is the same, in practical applications, can be for a variety of labels, to meet their own needs, such as code use frequency is very high, basically be for a few days time will be used, especially in large projects, PHP1 dimensional array, PHP2 dimensional array, or even PHP multidimensional arrays, all the time in programs are running.


Related articles: