PHP - 2D数组表格式

时间:2015-08-03 12:03:00

标签: php html arrays html-table

我有一个带有键的2D电影数组,这些键是通过MySQL Db通过phpMyAdmin生成的。

(从复制粘贴中删除的情节)

$films = array(
  array('title' => 'Batman Begins','yr' => '2005','genre' => 'Action, Adventure','plot' => 'After training with his mentor, Batman begins his w...')
  array('title' => 'Ted 2','yr' => '2015','genre' => 'Comedy','plot' => 'Newlywed couple Ted and Tami-Lynn want to have a baby, but in order to...')
  array('title' => 'Ted','yr' => '2012','genre' => 'Comedy, Fantasy','plot' => 'As the result of a childhood wish, John Bennett\'s teddy bear, ...')
  array('title' => 'Interstellar','yr' => '2014','genre' => 'Adventure, Sci-Fi','plot' => 'A team of explorers travel through a wormhole in spa...')
);

我还有一个foreach循环,循环遍历2D数组并将结果作为表格返回:

$out = "";
$out .= "<table>";
foreach($films as $key => $element){
  $out .= "<tr>";
  foreach($element as $subk => $subel){
    $out .= "<td>$subel</td>";
  }
  $out .= "</tr>";
}
$out .="<table>";

echo $out;

根据我在网页上看到的结果,显示如下:

蝙蝠侠2005年开始行动,冒险训练后......

我如何能够将密钥显示为列标题?我已尝试在主要循环中创建另一个foreach循环,但返回标题如下:titleyrgenreplottitleyrgenreplot等。

我如何才能在表格中正确格式化,以便出现标题?

这也只是一个小而快速的问题:我不是将数据库从phpMyAdmin导出为PHP数组,而是在MySQL数据库表中进行更改后如何更新PHP /网页?

2 个答案:

答案 0 :(得分:1)

以下是获取标题的方法:

$headers="<thead><tr>";
foreach($films as $key => $element){
   $headers.= "<th>$key</th>";
  }
$headers.= "</tr></thead>";

所以你的代码现在应该是这样的:

$out = "";
$out .= "<tbody>";
$headers="<table><thead><tr>";
foreach($films as $key => $element){
  $headers.= "<th>$key</th>";
  $out .= "<tr>";
  foreach($element as $subk => $subel){
      $out .= "<td>$subel</td>";
  }
  $out .= "</tr>";
}
$out .="</tbody><table>";
$headers.= "</tr></thead>";

echo $headers;
echo $out;

答案 1 :(得分:0)

为了将字段显示为标题,我们只需循环遍历第一个子数组的键,然后在循环遍历整个结果之前添加另一行(<tr>)和表头(<th>)。通常我们只显示一次标题。

 $out = "";
 $out .= "<table>";
 $out .= "<tr>";
 foreach($films[0] as $key => $value)
 {
   $out  .= "<th>".$key."</th>";
 }
 $out .= "</tr>";
 foreach($films as $key => $element){
  $out .= "<tr>";

  foreach($element as $subk => $subel){
   $out .= "<td>$subel</td>";
  }
  $out .= "</tr>";
 }
 $out .="<table>";

 echo $out;