Blogger Information
Blog 49
fans 0
comment 4
visits 41970
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用foreach/if替代语法循环遍历二维数组
过儿的博客
Original
1184 people have browsed it

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>

运行实例 »

点击 "运行实例" 按钮查看在线实例

d.png

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>

运行实例 »

点击 "运行实例" 按钮查看在线实例

输出结果与第一种完全一样!


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post