虽然是可能的,并不难达到你想要的使用PHP的结果,使用适当的查询,您的问题在数据库中更容易解决。
试试这个:
SELECT head, GROUP_CONCAT(name SEPARATOR '') AS all_names
FROM tbl
GROUP BY head
替换tbl
与实际的表名。您可能也希望以某种顺序得到结果。为此添加ORDER BY head
。
的PHP代码现在变为:
while ($row = $stmt->fetch()) {
echo("<div>{$row['head']}:{$row['all_names']}</div>");
}
这就是全部。
的PHP,唯一的解决办法就是保持head
当前值的轨道, 输出关闭标签</div>
当head
值更改但不是第一排,输出的开始标记<div>
之前也当值head
发生变化时。此外,只显示一次head
的值,当它更改时,将显示每行的值name
。不要忘记在循环结束后输出一个结束标记,但只有在迭代至少一次时(查询才返回)。
这听起来很困难,但其实是很容易的:
// The current value of $['head']
// We assume here NULL is not a valid value for it in the database
// If it happens that you have NULLs in the database in column "head"
// then make sure the query converts it to an empty string. For example:
// SELECT IFNULL(head, '') AS head ...
$head = NULL;
// Process one row at a time
while ($row = $stmt->fetch()) {
if ($row['head'] !== $head) {
// The value of 'head' just changed
// Display '</div>' but not before the first row
if ($head !== NULL) {
// This is not the first row, there is a current value of 'head'
echo("</div>\n");
}
// Display the opening tag '<div>' and new value of 'head', only once
echo("<div>{$row['head']}: ");
// Update the current value of 'head'
$head = $row['head']
}
// Display 'name'; there is nothing special here
echo($row['name']);
}
// After the loop, close the last <div> only if there is one ($head was changed)
if ($head !== NULL) {
echo("</div>\n");
}
而不是在上面的代码,你可以使用一些“神奇”的字符串NULL
(它被称为“前哨”),这是不可能的出现在数据库的head
列中。
你使用什么数据库系统?从数据库中获取已经组合的值比较容易。 – axiac
@axiac MYSQL(MariaDB) – Axon