我想从PHP关联数组
创建一个表这是我的代码:
$itemspecifics = array(
"Condition" => "New",
"Year" => "2007",
"Manufacturer" => "Audi",
"Model" => "A4",
"Type" => "Limousine",
"Options" => "Full"
);
我希望以这种格式生成一个表:
<table width="779" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="104">Condition</td>
<td width="318">New</td>
<td width="176">Year</td>
<td width="171">2007</td>
</tr>
<tr>
<td>Manufacturer</td>
<td>Audi</td>
<td>Model</td>
<td>A4</td>
</tr>
<tr>
<td>Type</td>
<td>Limousine</td>
<td>Options</td>
<td>Full</td>
</tr>
</table>
答案 0 :(得分:0)
从那个关联数组中,你必须得到键和值并将它们展平在另一个数组中,然后将它们分成四个。考虑这个例子:
关于PHP:
$itemspecifics = array(
"Condition" => "New",
"Year" => "2007",
"Manufacturer" => "Audi",
"Model" => "A4",
"Type" => "Limousine",
"Options" => "Full"
);
$data = array();
foreach($itemspecifics as $key => $value) {
$data[] = $key;
$data[] = $value;
}
$data = array_chunk($data, 4); // chunk them by four's
在HTML / PHP上:
<style>
.header{
background-color: green;
}
</style>
<!-- them loop them -->
<table border="1" cellpadding="10">
<?php foreach($data as $key => $value): ?>
<tr>
<?php foreach($value as $index => $element): ?>
<td class="<?php echo ($index % 2 == 0) ? 'header' : ''; ?>"> <!-- simple coloring -->
<?php echo $element; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>