当我打印出一张表时,我有一个查询给出了类似下面的结果:
+---------------------------------------------------------------------+
| ID | Name | Color | Size | Qty |
+---------------------------------------------------------------------+
| 1 | First | Green | S | 1 |
| 2 | First | Green | L | 2 |
| 3 | First | Green | XL | 1 |
| 4 | First | Red | M | 2 |
| 5 | First | Red | L | 3 |
| 6 | Second | Blue | S | 1 |
| 7 | Second | Blue | M | 4 |
+---------------------------------------------------------------------+
现在我想概述(在现实生活中这些是产品),有人可以点击按钮进行编辑或删除。我想用foreach循环或其他东西循环它并打印出类似这样的东西:
+========================================================================+
| Name | Color | Size | Qty | Action |
+========================================================================+
| First | Green | S | 1 | Edit|Delete |
| | | L | 2 | Edit|Delete |
| | | XL | 1 | Edit|Delete |
+------------------------------------------------------------------------+
| First | Red | M | 2 | Edit|Delete |
| | | L | 3 | Edit|Delete |
+------------------------------------------------------------------------+
| Second | Blue | S | 1 | Edit|Delete |
| | | M | 4 | Edit|Delete |
+------------------------------------------------------------------------+
但不知何故,我无法理解如何编程这个循环。或者我应该更改查询? 我希望有人能帮帮忙。如果您需要更多信息,请告诉我。
答案 0 :(得分:0)
您可以在数据库中执行此操作,这样可以更轻松地在代码中显示数据:
select
group_concat(ID) as id,
name,
color,
group_concat(size) as size,
group_concat(qty) as qty
from
myTable
group by
name,
color
结果如下:
ID | name | color | size | qty
1,2,3 | First | Green | S,L,XL | 1,2,1
etc...
现在,在您的代码中,这样可以更轻松地按照您希望的方式输出。
echo "<table>";
while($row=someFetchFromDatabase($results))
{
echo "<tr><td>".$row['name']."</td><td>".$row['color']."</td>";
$temp=explode($row['size']);
echo "<td>";
foreach($temp as $val)
{
echo $val."<br>";
}
echo "</td>";
$temp=explode($row['qty']);
echo "<td>";
foreach($temp as $val)
{
echo $val."<br>";
}
echo "</td>";
$temp=explode($row['IDs']);
echo "<td>";
foreach($temp as $val)
{
echo "<a href='someLink.php?action=edit&ID=".$val."'>Edit</a> | <a href='someLink.php?action=delete&ID=".$val."'>Delete</a>";
}
echo "</td></tr>";
}
echo "</table>'
答案 1 :(得分:0)
我不会对查询做任何事情。
在伪代码中(我不会说PHP)...
variables $name = "", $colour = "";
for (every row)
if (row.name = $name) and (row.colour = $colour)
display nothing for name and colour
else
display row.name
display row.colour
$name = row.name
$colour = row.colour