PHP - 2D数组表格式


PHP - 2D Array table formatting

我有一个2D数组的电影与键是通过phpMyAdmin通过MySQL数据库生成的。

(从复制粘贴中切断绘图)

$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循环,循环通过二维数组,并返回结果作为一个表:

$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,,,动作冒险   After training…

我如何能够显示键作为列标题?我试过在主循环中制作另一个foreach循环,但它返回了这样的标题:titleyrgenreplottitleyrgenreplot等。

我如何能够正确格式化它在一个表,所以标题出现?

也只是一个小的,快速的问题:而不是从phpMyAdmin导出数据库作为一个PHP数组,我如何能够更新PHP/网页时,已在MySQL数据库表的变化?

获取标题的方法如下:

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

为了显示字段作为标题,我们只需要循环通过第一个子数组的键并添加另一行(<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;