【发布时间】:2014-08-01 17:55:18
【问题描述】:
我正在尝试从从 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>
【问题讨论】:
-
您正在为
foreach()中迭代的每个项目打开一个<tr>,但您只在循环外关闭一次</tr>。我看不到您的示例输出与代码的对应关系。 -
发布的结果是最终结果还是您已经发布了部分结果???正如您提到的那样,它会生成一个很长的表格。
-
我想看看
$rows的样子 -
Kender,
$row->special_features是一个带有逗号分隔符的字符串,类似于Auto Pilot,Red,Dual Cores,Grey,然后我使用 inarray 检查来自$featured_tests的每个数组元素是否存在于$row->special_features中。