我试图从mysql提取的返回数据中获取此输出:
<table>
<thead>
<tr>
<th></th><th><img src='img1.jpg'></th><th><img src='img2.jpg'></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan='5'>Features</td>
<td>LCD</td><td>Yes</td><td>No</td>
<td>Auto Pilot</td><td>No</td><td>No</td>
<td>Fast Generation</td><td>Yes</td><td>No</td>
<td>Dual Cores</td><td>No</td><td>Yes</td>
</tr>
</tbody>
</table>
但是我无法通过一个foreach循环获得以下代码来实现该输出。它使用in_array
来检查返回的数据中是否存在$ featured_tests中的每个值。
$featured_tests = array("LCD","Auto Pilot","Fast Generation","Dual Cores");
$table_head ="<table><thead><tr><th></th>";
$table_colspan1 = "</tr></thead><tbody><tr><td colspan='5'>Features</td></tr>";
$table_end ="</tr></tbody></table>";
foreach($rows as $row)
{
$special_features = explode(",",$row->special_features);
$header_image .= "<th><img src='".$row->image_url."'></th>";
foreach($featured_tests as $featured_test)
{
$featured .= "<tr><td>".$featured_test."</td>";
if(in_array($featured_test,$special_features))
{
$featured .= "<td>Yes</td>";
}
else
{
$featured .= "<td>No</td>";
}
}
}
$table_html = $table_head.$header_image.$table_colspan1.$featured.$table_end;
但我得到的结果是一团糟。 $featured_tests
中的每个值都会针对每个产品反复迭代,从而产生一个非常长的表。任何人都可以帮我纠正我的代码以获得理想的输出吗?
结果如下:
<table>
<thead>
<tr>
<th></th><th><img src='img1.jpg'></th><th><img src='img2.jpg'></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan='5'>Features</td>
</tr>
<tr>
<td>LCD</td><td>Yes</td>
</tr>
<tr>
<td>Auto Pilot</td>No<td></td>
</tr>
<tr>
<td>Fast Generation</td><td>Yes</td>
</tr>
<tr>
<td>Dual Cores</td>No<td>
</tr>
<tr>
<td>LCD</td><td>No</td>
</tr>
<tr>
<td>Auto Pilot</td>No<td></td>
</tr>
<tr>
<td>Fast Generation</td><td>No</td>
</tr>
<tr>
<td>Dual Cores</td>Yes<td>
</tr>
</tbody>
</table>
答案 0 :(得分:0)
你正在最深刻的foreach中创建新行<tr>
...
以这个例子来制作你想要的东西:
<table>
<thead>
<th>Col 1</th><th>Col 2</th>
</thead>
<tbody>
<?php foreach($large_array as $less_array): ?>
<tr>
<?php foreach($less_array as $row): ?>
<!-- <td> contents etc</td>-->
<?php endforeach?>
</tr>
<?php endforeach;?>
</tbody>
</table>