php 自定义函数的应用
动态生成表格
<?php
$arrHead = [
'姓名',
'性别',
'年龄'
];
$arrData = [
[
'name'=>'张三',
'sex'=>'男',
'age'=>23
],
[
'name'=>'小美',
'sex'=>'女',
'age'=>18
],
[
'name'=>'大漂亮',
'sex'=>'女',
'age'=>19
],
[
'name'=>'李四',
'sex'=>'男',
'age'=>32
]
];
//自定义函数createTable,用于动态创建表格
function createTable($head,$data,$style){
$table =' <table style="background-color:' . $style . '">';
$table .=' <theader>';
$table .=' <tr>';
//填充表头
foreach ($head as $head_k => $head_v) {
$table .=' <th>' . $head_v . '</th>';
}
$table .=' </tr>';
$table .=' </theader>';
$table .=' <tbody>';
//循环行
foreach ($data as $data_k => $data_v) {
$table .=' <tr>';
//循环填充每行中的单元格数据
foreach($data_v as $data_kk=>$data_vv){
$table .= ' <td>' . $data_vv .'</td>';
}
$table .=' </tr>';
}
$table .=' </tbody>';
$table .=' </table>';
return $table;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>table</title>
<style>
table{
margin:2em auto;
border-collapse:collapse;
}
th,td{
width: 100px;
border:1px solid black;
}
</style>
</head>
<body>
<?php echo createTable($arrHead,$arrData,'lightgreen'); ?>
</body>
</html>
运行结果: