問題描述
一個簡單的谷歌搜索將揭示多種使用 PHP 將二維數組轉換為 HTML 的解決方案.不幸的是,這些都沒有我正在尋找的答案.
A simple Google search will reveal a multitude of solutions for converting a two dimension array into HTML using PHP. Unfortunately none of these has the answers I am looking for.
我想要一段將數組轉換為 HTML 表格的通用代碼.大多數例子出錯的地方是他們假設程序員知道表的字段的名稱.我希望這段代碼是通用的,這樣即使我不知道字段的名稱,我也可以使用它.
I want a generic piece of code that converts an array into a HTML table. Where most examples go wrong is that they assume the programmer knows the name of the table's fields . I want this code to be generic such that I can use it even if I do not know the name of the fields.
我可以看到我需要兩個循環.一個嵌套在另一個里面.鑒于我不知道密鑰,我不確定如何獲取值.
I can see I need two loops. One nested inside of the other. What I am not sure of is how to get the values out given I don't know the keys.
最終結果有望輸出這樣的html:
The end result will hopefully output html something like this:
<th>
<td>x/y</td>
<td> x1 </td>
<td> x2 </td>
</th>
<tr>
<td>y1</td>
<td> x1y1 </td>
<td> x2y1 </td>
</tr>
<tr>
<td>y2</td>
<td> x1y2 </td>
<td> x2y2 </td>
</tr>
請記住,我想要一個通用且簡單的解決方案.我希望這很清楚.
Please remember I want a generic and simple solution. I hope this is clear.
推薦答案
下面的代碼將遍歷數組的兩個維度,并將它們變成一個表格.不管 key
是什么,你都會得到它的可視化表示.如果它們確實有鍵名而不僅僅是索引,則這些值將分別在$key
和$subkey
中可用.所以如果你需要它們,你可以擁有它們.
The following code will look through the two dimensions of the array and make them into a table. Regardless of what the key
may be, you will get a visual representation of it. If they do have key name and not just an index, the values will be available in $key
and $subkey
respectively. So you have them if you need them.
代碼:
$myarray = array("key1"=>array(1,2,3,4),
"key2"=>array(2,3,4,5),
"key3"=>array(3,4,5,6),
"key4"=>array(4,5,6,7)); //Having a key or not doesn't break it
$out = "";
$out .= "<table>";
foreach($myarray as $key => $element){
$out .= "<tr>";
foreach($element as $subkey => $subelement){
$out .= "<td>$subelement</td>";
}
$out .= "</tr>";
}
$out .= "</table>";
echo $out;
結果:
如果您想將鍵視為標題,可以在 echo "