2015-08-03 58 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 *的新手誰不瞭解你所做的。 –