将PHP二维数组转换为HTML [英] PHP two dimensional array into HTML
问题描述
我需要一个将数组转换为HTML表的通用代码片段。大多数例子出错的地方在于,他们假设程序员知道表格字段的名称。我希望此代码是通用的,这样即使我不知道字段名称,也可以使用它。
我可以看到我需要两个循环。一个嵌套在另一个内部。我不确定的是如何获取值,因为我不知道密钥。
最终结果将希望输出html像这样:
p> < 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>
请记住我想要一个通用而简单的解决方案。我希望这很清楚。
以下代码将查看数组的两个维度并将它们放入一个表中。无论键
可能是什么,您都可以看到它。如果他们 do 具有关键名称而不仅仅是索引,则这些值将在 $ key
和 $ subkey
。所以,如果你需要它们,你可以购买它们。
代码:
<$ p $ (2,3,4,5),
key2=>数组(2,3,4,5) ,
key3=>数组(3,4,5,6),
key4=>数组(4,5,6,7)); //有或没有钥匙不会破坏它
$ out =;
$ out。=< table>;
foreach($ myarray as $ key => $ element){
$ out。=< tr>;
foreach($ element as $ subkey => $ subelement){
$。=< td> $ subelement< / td>;
}
$ out。=< / tr>;
}
$ out。=< / table>;
echo $ out;
结果:
如果您希望将键看作标题,您可以在 echo< table>;
行后添加此代码:
echo< tr>;
foreach($ myarray as $ key => $ element)echo< td> $ key< / td>;
回声< / tr>;
导致:
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.
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.
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.
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.
The code:
$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;
The result:
If you want to see the keys as headings, you could add this code after the echo "<table>";
line:
echo "<tr>";
foreach($myarray as $key => $element) echo "<td>$key</td>";
echo "</tr>";
Resulting in this:
这篇关于将PHP二维数组转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!