2015-08-03 56 views
1

我有一个电影的二维数组与密钥,这是通过MySQL DBB通过phpMyAdmin生成的。PHP - 二维数组表格格式

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

而且从结果我的网页上看到,显示的是这样的:

蝙蝠侠       动作,冒险     训练结束后...

我怎么能够显示键的列标题?我已经尝试在主要内部制作另一个foreach循环,但返回的标题如下:titleyrgenreplottitleyrgenreplot

我该如何在表格中正确设置格式,以便标题出现?

同样只是一个小问题,而不是从phpMyAdmin将数据库导出为PHP数组,如何在MySQL数据库表中进行更改时能够更新PHP /网页?

回答

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

为显示领域的头,我们只需要遍历1的键子阵列,并在循环遍历整个结果之前在表格标题(<th>)中添加另一行(<tr>)。通常我们只显示头一次。

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

OP为什么要“试试这个”?一个好的答案将总是解释做了什么以及为什么这样做,不仅是为了OP,而且是为了将来SO的访问者。 –

+0

正如你所看到的@JayBlanchard。这似乎是非常直接的循环问题。所以我只是回答了询问者。不过,我会采纳你的建议并更新我的答案。 –

+0

我明白这很简单,但是考虑一下将会有* n *的新手谁不了解你所做的。 –