如何从PHP数组创建HTML表格?

46

我该如何从PHP数组创建一个HTML表格?一个包含标题为'title''price''number'的表格。

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

4
这个问题与https://dev59.com/X2445IYBdhLWcg3wq8Lp完全相同。请不要重复发布问题 - 您只是浪费自己(和其他人的)时间。 - John Parker
5
合并完成。祈祷我不会再次合并! - user1228
此线程已在此处得到解答 点击这里 - Delickate
18个回答

94

最好的方法是像这样将数据直接存入数组中:

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

2
创建表的智能方式。我基于你的代码创建了一个有用的函数。谢谢。 - sdespont
3
array_map()函数返回一个数组,而且$row并没有通过引用传递,所以这行代码基本上什么也没做,对吧? - syaz
1
有人能解释一下 array_map('htmlentities', $row) 吗?我不太理解。 - Galang Re
2
@Timo 一个视图/控制器类型的框架对于中大型项目非常好(Twig是一个很棒的语言和工具)。对于小型项目,在我看来混合代码也没问题,但绝不能触碰“?>”特性,也不要关闭php解释器。否则你最终会得到令人尴尬的意大利面式代码。当招聘时,这样的代码是我拒绝一个人而无需进一步提问的原因。 - John
2
@timo 别关闭 PHP 解释器,那是非常丑陋的 1994 年脚本编写方式。只需创建一个输出 HTML 的函数(echo),或将 echo 放入你的代码中即可。如果你的项目变得更大,请使用类似 twig 的工具。 - John
显示剩余7条评论

42

这是我的:

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

这很简单而且有用。谢谢。 - relipse
我创建了一个更通用的答案版本。这是链接 - https://dev59.com/X2445IYBdhLWcg3wq8Lp#68557121 - Pavan Yogi

19
   <table>
     <tr>
       <td>title</td>
       <td>price</td>
       <td>number</td>
     </tr>
     <? foreach ($shop as $row) : ?>
     <tr>
       <td><? echo $row[0]; ?></td>
       <td><? echo $row[1]; ?></td>
       <td><? echo $row[2]; ?></td>
     </tr>
     <? endforeach; ?>
   </table>

5
模板标签有什么问题吗? @HalfCrazed - Kumar Ravi
3
翻译:不是所有系统都支持短标签。 - DarkMukke

15

你还可以使用 array_reduce

array_reduce — 使用回调函数逐步将数组简化为单一的值

例如:

$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";

echo "<table>\n$thead\n$tbody\n</table>";

1
尽管这只有三行,但从某种意义上说,它是最干净的解决方案,因为它使用了适当的PHP结构来完成工作。 - papo

8

这是一种最好、最简单和最有效的方法之一。 您可以将数组转换为具有任意列数或行数的表格。 它以数组键作为表头。无需使用array_map。

function array_to_table($matriz) 
{   
   echo "<table>";

   // Table header
        foreach ($matriz[0] as $clave=>$fila) {
            echo "<th>".$clave."</th>";
        }

    // Table body
       foreach ($matriz as $fila) {
           echo "<tr>";
           foreach ($fila as $elemento) {
                 echo "<td>".$elemento."</td>";
           } 
          echo "</tr>";
       } 
   echo "</table>";}

5
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
    echo "<tr>";
    foreach($v as $vv){
        echo "<td>{$vv}</td>";
    }
    echo "<tr>";
}
echo "</table>";

4
echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
    echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';

3
    <table>
      <thead>
        <tr><th>title</th><th>price><th>number</th></tr>
      </thead>
      <tbody>
<?php
  foreach ($shop as $row) {
    echo '<tr>';
    foreach ($row as $item) {
      echo "<td>{$item}</td>";
    }
    echo '</tr>';
  }
?>
      </tbody>
    </table>

3

Here is my answer.

function array2Html($array, $table = true)
{
    $out = '';
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (!isset($tableHeader)) {
                $tableHeader =
                    '<th>' .
                    implode('</th><th>', array_keys($value)) .
                    '</th>';
            }
            array_keys($value);
            $out .= '<tr>';
            $out .= array2Html($value, false);
            $out .= '</tr>';
        } else {
            $out .= "<td>".htmlspecialchars($value)."</td>";
        }
    }

    if ($table) {
        return '<table>' . $tableHeader . $out . '</table>';
    } else {
        return $out;
    }
}

然而,你的表头必须是数组的一部分,这在从数据库中获取数据时非常常见。例如:
$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,
    ),
);

print array2Html($shop);

希望这能有所帮助 ;)

你忘记对字符串进行htmlspecialchars编码,因此除非你传递一个不编码的选项,否则数据应该被编码。 - Timo Huovinen
我有三个问题,第一个是我得到了与上面相同的结果,第二个是递归在这里是如何工作的?递归何时停止?我认为两个返回语句是停止递归的地方,函数最终以$ table true运行而不是循环并返回表格。第三个是您代码中的小错误,请修复函数的调用名称。 - Timo
@TimoHuovinen,也许你可以就我的评论提供帮助。 - Timo

2

您可以使用这个函数。如果要添加表头,您可以设置第二个参数$myTableArrayHeader,并在正文前面做相同的操作来设置表头信息:

function insertTable($myTableArrayBody) {
    $x = 0;
    $y = 0;
    $seTableStr = '<table><tbody>';
    while (isset($myTableArrayBody[$y][$x])) {
        $seTableStr .= '<tr>';
        while (isset($myTableArrayBody[$y][$x])) {
            $seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
            $x++;
        }
        $seTableStr .= '</tr>';
        $x = 0;
        $y++;
    }
    $seTableStr .= '</tbody></table>';
    return $seTableStr;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接