【问题标题】:PHP - 2D Array table formattingPHP - 二维数组表格格式
【发布时间】:2015-10-25 12:42:15
【问题描述】:

我有一个二维电影数组,其中包含通过 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/网页?

【问题讨论】:

    标签: php html arrays html-table


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 为什么 OP 应该“试试这个”?一个好的答案总是会解释所做的事情以及这样做的原因,不仅适用于 OP,而且适用于 SO 的未来访问者。
      • 如您所见@JayBlanchard。这似乎是一个非常直接的循环问题。所以我只是回答了询问者。但是,我会听取您的建议并更新我的答案。
      • 我知道这很简单,但考虑到会有 n 个新手不会理解您所做的事情。
      • 我会强调这一点,我会解释我的每一个答案,以便它对其他人也有帮助。谢谢@JayBlanchard
      猜你喜欢
      • 2014-11-02
      • 1970-01-01
      • 2021-04-07
      • 2018-07-21
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2022-07-08
      • 2017-03-14
      相关资源
      最近更新 更多