dongshen6060 2015-08-03 12:03
浏览 28
已采纳

PHP - 2D数组表格式

I've got a 2D array of movies with keys which was generated via phpMyAdmin via a MySQL Db.

(Plot cut off from copy pasting)

$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...')
);

I've also got a foreach loop, to loop through the 2D array and return the results as a table:

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

And from the results I see on the web page, this displays it like this:

Batman Begins     2005     Action, Adventure     After training ...

How would I be able to display the key as the column header? I've tried making another foreach loop inside the main one, but that returned the header like this: titleyrgenreplottitleyrgenreplot etc.

How would I be able to properly format it in a table, so headers appear?

Also just a small, quick question: instead of exporting the database from phpMyAdmin as a PHP array, how would I be able to update the PHP/webpage when a change has been made in the MySQL database table?

  • 写回答

2条回答 默认 最新

  • dongyu9667 2015-08-03 12:08
    关注

    here is how you will get your headers:

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

    So your code should now look like:

    $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条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站