Home  >  Article  >  Backend Development  >  How to use foreach() to traverse two-dimensional and multi-dimensional arrays

How to use foreach() to traverse two-dimensional and multi-dimensional arrays

伊谢尔伦
伊谢尔伦Original
2017-06-22 17:38:537369browse

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(&#39;lk&#39;,&#39;ok&#39;);
//$book = array(&#39;linux服务器配置与管理&#39;,$team);
$arr = array(
array(&#39;name&#39;=>&#39;系统配置&#39;,&#39;url&#39;=>&#39;?action=config&do=config&#39;),
array(&#39;name&#39;=>&#39;验证码配置&#39;,&#39;url&#39;=>&#39;?action=config&do=seccode&#39;),
array(&#39;name&#39;=>&#39;模板管理&#39;,&#39;url&#39;=>&#39;?action=config&do=tpl&#39;),
array(&#39;name&#39;=>&#39;帐号管理&#39;,&#39;url&#39;=>&#39;?action=admin&do=list&#39;),
array(&#39;name&#39;=>&#39;添加帐号&#39;,&#39;url&#39;=>&#39;?action=admin&do=add&#39;));
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,&#39;2468246&#39;,"salkh@bbs.com"), 
array(2,&#39;343681643&#39;,"aikdki@sina.com"), 
array(3,&#39;3618468&#39;,"42816@qq.com") 
) 
); 
//循环遍历,输出一个表格 
foreach($info as $tableName=>$table){ 
echo "<table align=&#39;center&#39; border=&#39;1&#39; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn