如何从 PHP 数组创建 HTML 表? [英] How to create a HTML Table from a PHP array?

查看:25
本文介绍了如何从 PHP 数组创建 HTML 表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 PHP 数组创建 HTML 表格?标题为'title''price''number'的表格.

How do I create a HTML table from a PHP array? A table with heading as 'title', 'price', and 'number'.

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
); 

推荐答案

最好像这样将数据提取到数组中:

It would be better to just fetch the data into array like this:

<?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) 
             ); 
?>

然后执行类似的操作,即使您稍后向数据库中的表添加更多列,它也应该可以正常工作.

And then do something like this, which should work well even when you add more columns to your table in the database later.

<?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 数组创建 HTML 表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆