我有一个名为$ properties的数组,如下所示
Array
(
[car] => array
(
[0] => Array (
[brand] => feature1
[material] => material1
[type] => type1
)
[1] => Array (
[brand] => feature2
[material] => material2
[type] => type2
)
)
[bus] => array
(
[0] => Array (
[brand] => feature3
[material] => material3
[type] => type3
)
[1] => Array (
[brand] => feature4
[material] => material4
[type] => type4
)
)
)
遍历上面的数组,以便显示多个表格形式。有什么办法吗?
答案 0 :(得分:0)
步骤1:创建数组:
$arr = array('car' => array('0' => array('brand' => 'feature1','material' => 'material1','type' => 'type1'),
'1' => array('brand' => 'feature2','material' => 'material2','type' => 'type2'),
'2' => array('brand' => 'feature3','material' => 'material3','type' => 'type3')),
'bus' => array('0' => array('brand' => 'feature4','material' => 'material4','type' => 'type4'),
'1' => array('brand' => 'feature5','material' => 'material5','type' => 'type5'),
'2' => array('brand' => 'feature6','material' => 'material6','type' => 'type6')));
第2步:遍历数组:
foreach ($arr as $veh){
foreach($veh as $det){
echo $det['brand'].' '.$det['material'].' '.$det['type'].'<br>';
}
}
输出
feature1 material1 type1
feature2 material2 type2
feature3 material3 type3
feature4 material4 type4
功能5材质5类型5
feature6 material6 type6
复制以下代码,并将其另存为.php。 显示为表格:
<?php
$arr = array('car' => array('0' => array('brand' => 'feature1','material' => 'material1','type' => 'type1'),
'1' => array('brand' => 'feature2','material' => 'material2','type' => 'type2'),
'2' => array('brand' => 'feature3','material' => 'material3','type' => 'type3')),
'bus' => array('0' => array('brand' => 'feature4','material' => 'material4','type' => 'type4'),
'1' => array('brand' => 'feature5','material' => 'material5','type' => 'type5'),
'2' => array('brand' => 'feature6','material' => 'material6','type' => 'type6')));
echo '<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>';
foreach ($arr as $veh){
echo '<h1>'.array_search ($veh, $arr).'</h1>';
echo '<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>';
foreach($veh as $det){
echo '<tr>
<td>'.$det['brand'].'</td>
<td>'.$det['material'].'</td>
<td>'.$det['type'].'</td>
</tr>';
// echo $det['brand'].' '.$det['material'].' '.$det['type'].'<br>';
}
echo '</table>
</body>
</html>';
}
?>