如何从PHP数组创建HTML表?
如何从 PHP 数组创建 HTML 表?标题为“标题”、“价格”和“数字”的表格。
$shop = array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7 ),
);
如何从 PHP 数组创建 HTML 表?标题为“标题”、“价格”和“数字”的表格。
$shop = array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7 ),
);
最好像这样将数据提取到数组中:
<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
array("title"=>"daisy", "price"=>0.75 , "number"=>25),
array("title"=>"orchid", "price"=>1.15 , "number"=>7)
);
?>
然后执行类似操作,即使以后向数据库中的表中添加更多列,这些操作也应该很有效。
<?php if (count($shop) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
这是我的:
<?php
function build_table($array){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . htmlspecialchars($key) . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
$array = array(
array('first'=>'tom', 'last'=>'smith', 'email'=>'tom@example.org', 'company'=>'example ltd'),
array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh@example.org', 'company'=>'example ltd'),
array('first'=>'steph', 'last'=>'brown', 'email'=>'steph@example.org', 'company'=>'example ltd')
);
echo build_table($array);
?>