Home > Article > Backend Development > How to use foreach() to traverse two-dimensional and multi-dimensional arrays
The first type
I want to use foreach() to traverse the entire two-dimensional array:
$team = array('lk','ok'); $book = array('linux服务器配置与管理',$team); foreach($book as $k=>$val) //for $book each $value( as ) echo $k.'=>'.$val.'';
The output result is:
0=>linux server configuration and management
1=>Array
Of course, I actually want all the specific content, not the output array. . .
So the following approach should be adopted, adding a judgment statement:
$team = array('lk','ok'); $book = array('linux服务器配置与管理',$team); foreach($book as $k=>$val) //意思是for $book each $value( as ) if( is_array($val) ) foreach( $val as $value) echo $value.''; else echo $k.'=>'.$val.'';
The output is:
0=>linux server configuration With management
lk
ok
echo "<br>"; echo "<h1>php遍历二维数组</h1>"; //$team = array('lk','ok'); //$book = array('linux服务器配置与管理',$team); $arr = array( array('name'=>'系统配置','url'=>'?action=config&do=config'), array('name'=>'验证码配置','url'=>'?action=config&do=seccode'), array('name'=>'模板管理','url'=>'?action=config&do=tpl'), array('name'=>'帐号管理','url'=>'?action=admin&do=list'), array('name'=>'添加帐号','url'=>'?action=admin&do=add')); foreach($arr as $k=>$val){ echo "name:".$val["name"]."/n"; }
The second type
foreach() traverses multidimensional array:
<?php //声明一个三维数组 $info=array( "user"=>array( array(1,"zhangsan",20,"nan"), array(2,"lisi",20,"nan"), array(3,"wangwu",25,"nv") ), "score"=>array( array(1,100,98,95,96), array(2,56,98,87,84), array(3,68,75,84,79) ), "connect"=>array( array(1,'2468246',"salkh@bbs.com"), array(2,'343681643',"aikdki@sina.com"), array(3,'3618468',"42816@qq.com") ) ); //循环遍历,输出一个表格 foreach($info as $tableName=>$table){ echo "<table align='center' border='1' width=300>"; echo "<caption><h1>".$tableName."</h1></caption>";//以每个数组的键值作为表名 foreach($table as $row){ echo "<tr>"; foreach($row as $col){ echo "<td>".$col."</td>"; } echo "</tr>"; } echo "</table>"; } ?>
The above is the detailed content of How to use foreach() to traverse two-dimensional and multi-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!