时间:2021-07-01 10:21:17 帮助过:40人阅读
想用foreach()遍历整个二维数组:
$team = array('lk','ok'); $book = array('linux服务器配置与管理',$team); foreach($book as $k=>$val) //for $book each $value( as ) echo $k.'=>'.$val.'';
输出结果是:
0=>linux服务器配置与管理
1=>Array
当然,其实我是想要所有具体内容,而不是输出array。。。
所以应该采用如下做法,加入一个判断语句:
$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.'';
则输出为:
0=>linux服务器配置与管理
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"; }
第二种类型
foreach()遍历多维数组:
<?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>"; } ?>
以上就是如何使用foreach()遍历二维数组和多维数组的详细内容,更多请关注Gxl网其它相关文章!