语法:
foreach 替代语法: <?php foreach($users as $value): ?> // foreach 开始 <?php foreach($users as $key=>$value): ?> <?=$value['id'] ?> //输出数组值 <?=$key ?> //输出数组键 <?php endforeach; ?> // foreach 结束 if 替代语法: <?php if(判断条件): ?> 结果1 <?php else: ?> 结果2 <?php endif; ?>
代码: <?php // 定义变量 $title = '员工信息展示'; $thead = '员工信息表'; $users = [ ['id'=>1,'name'=>'张三','sex'=>1,'age'=>22,'email'=>'123435@qq.com'], ['id'=>2,'name'=>'李四','sex'=>1,'age'=>21,'email'=>'54354@qq.com'], ['id'=>3,'name'=>'王五','sex'=>0,'age'=>12,'email'=>'34232@qq.com'], ['id'=>4,'name'=>'赵六','sex'=>1,'age'=>32,'email'=>'54353@qq.com'], ['id'=>5,'name'=>'李一','sex'=>0,'age'=>22,'email'=>'658709@qq.com'] ]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- 使用PHP变量代替数据 --> <title><?=$title ?></title> <link rel="stylesheet" href="https://res.layui.com/layui/dist/css/layui.css?t=1545041465480" media="all"> <style> h3{text-align:center;line-height:40px;font-size:20px;} .layui-table{text-align:center;width:500px;margin:0 auto;} </style> </head> <body> <!-- 使用PHP变量代替数据 --> <h3><?=$thead ?></h3> <table class="layui-table" lay-even> <thead> <tr> <th>ID</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>邮箱</th> </tr> </thead> <tbody> <!-- 使用 foreach 替代语法遍历数组 --> <?php foreach($users as $user): ?> <tr> <td><?=$user['id'] ?></td> <td><?=$user['name'] ?></td> <!-- 使用 if 替代语法 --> <td> <?php if($user['sex']==1): ?> 男 <?php else: ?> 女 <?php endif; ?> </td> <td><?=$user['age'] ?></td> <td><?=$user['email'] ?></td> </tr> <?php endforeach; ?> </tbody> </table> </body> </html>
运行结果: