1、使用foreach语句循环输出二维数组信息
实例
<?php $title = "人名单"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $title; ?></title> </head> <body> <?php $arr = array( ['id'=>1,'name'=>'王二','sex'=>'男','age'=>'22'], ['id'=>2,'name'=>'王三','sex'=>'女','age'=>'23'], ['id'=>3,'name'=>'王四','sex'=>'男','age'=>'24'], ['id'=>4,'name'=>'王五','sex'=>'女','age'=>'21'] ); ?> <table border="1"> <tr><td>id</td><td>姓名</td><td>性别</td><td>年龄</td></tr> <?php $data = ''; foreach($arr as $array){ $data .='<tr>'; $data .= '<td>'.$array['id'].'</td>'; $data .= '<td>'.$array['name'].'</td>'; $data .= '<td>'.$array['sex'].'</td>'; $data .= '<td>'.$array['age'].'</td>'; $data .= '</tr>'; } echo $data; ?> </table> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
2、不使用大括号的foreach循环输出(结合if语句)
实例
<?php $title = "人名单"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $title; ?></title> </head> <body> <?php $arr = array( ['id'=>1,'name'=>'王二','sex'=>1,'age'=>'22'], ['id'=>2,'name'=>'王三','sex'=>0,'age'=>'23'], ['id'=>3,'name'=>'王四','sex'=>1,'age'=>'24'], ['id'=>4,'name'=>'王五','sex'=>0,'age'=>'21'] ); ?> <table border="1"> <tr><td>id</td><td>姓名</td><td>性别</td><td>年龄</td></tr> <?php foreach($arr as $array): ?> <tr><td><?=$array['id'];?></td><td><?=$array['name'];?></td><td><?=$array['sex'] ? '男':'女'; ?> </td><td><?=$array['age'];?></td></tr> <?php endforeach; ?> </table> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
输出结果与第一种完全一样!