我正在使用短代码写一个单词press plugin。 我有一个像这样的数组:
$data = array(
0 => array('name' => 'Jonh', 'birth' => 1985, 'number' => 6),
1 => array('name' => 'Marry', 'birth' => 1991, 'number' => 10),
2 => array(same above),
3 => array(same above)
.......................
);
如何使用foreach循环或任何方式返回(不回显)这样的表:
<table>
<tr>
<th>Name</th>
<th>Birth</th>
<th>Number</th>
</tr>
<tr>
<td>Show $data[0]['name']</td>
<td>Show $data[0]['birth']</td>
<td>Show $data[0]['number']</td>
</tr>
<tr>
Show all keys and all values of $data same above into each <tr> tags
</tr>
</table>
非常感谢!
答案 0 :(得分:2)
你可以做这样的事情
$data = array(
0 => array('name' => 'Jonh', 'birth' => 1985, 'number' => 6),
1 => array('name' => 'Marry', 'birth' => 1991, 'number' => 10),
2 => array(same above),
3 => array(same above)
);
$str="<table><tr>";
$str.="<th>Name</th>";
$str.="<th>Birth</th>";
$str.="<th>Number</th></tr>";
foreach ($data as $key => $value) {
# code...
$str.="<tr>";
$str.="<td>Show $data['name']</td>";
$str.="<td>Show $data['birth']</td>";
$str.="<td>Show $data['number']</td></tr>";
}
return $str;
答案 1 :(得分:1)
对我来说,最好的方法是将你的表放在var中并逐行创建,如下所示:
`
$data = array(
0 => array('name' => 'Jonh', 'birth' => 1985, 'number' => 6),
1 => array('name' => 'Marry', 'birth' => 1991, 'number' => 10)
);
$myTable = "
<table>
<tr>
<th>Name</th>
<th>Birth</th>
<th>Number</th>
</tr>";
foreach($data as $key => $value)
{
$myTable .= "
<td>Show ".$value['name']."</td>
<td>Show ".$value['birth']."</td>
<td>Show ".$value['number']."</td>
</tr>";
}
$myTable.="</table>";
echo $myTable; //You can also return it
`