我有以下代码:
SELECT q21, q21coding AS Description FROM `tresults_acme` WHERE q21 IS NOT NULL AND q21 <> '' ORDER BY q21coding
它带回了以下内容(摘录):
Text Description
Lack of up to date equal pay cases&legislation - t... Content needs updating
The intranet could contain more "up to date traini... Content needs updating
Poorly set out. It is hard to find things. Difficulty in navigating/finding content
Only use the intranet as a necessity. Will ask my ... Difficulty in navigating/finding content
现在,我想在PHP页面的表格中显示它,但由于我希望它显示的方式出现问题,它需要如下:
Content needs updating
----------------------
[List all the comments relating to this description]
Difficulty in navigating/finding content
----------------------------------------
[List all the comments relating to this description]
等等。
现在我认为它是PHP中的For Each循环,但是我很难理解这一点 - 非常欢迎任何想法和建议!
谢谢,
答案 0 :(得分:2)
prev_desc
设为NULL
text
description
不等于prev_desc
前置新“部分”的说明并设置prev_desc <- description
例如 1 (未经测试!),
$prev_desc = null;
while ($row = mysql_fetch_assoc(...)) {
if ($prev_desc != $row['description']) {
print '<h1>' . $row['description'] . '</h1>';
$prev_desc = $row['description'];
}
print $row['text'] . '<br />'; // Formatting needed
}
注意:您必须保留ORDER BY <description-column>
才能让行“分组”。否则这种简单的方法将无效。
我可以被认为更“干净”来创建某种2D容器来“分类”提取的数据,例如,
$items = array(
'Content needs updating' => array(
'Lack of ...',
'The intra...'
),
...
);
然后你可以循环遍历这些项目,如 1 :
foreach ($items as $desc => $texts) {
print '<h1>' . $desc . '</h1>';
foreach ($texts as $text) {
print $text . '<br />';
}
}
1 正如@bobince所指出的那样,确保直接进入最终HTML的内容被正确转义,例如, htmlspecialchars()
答案 1 :(得分:0)
您只需跟踪上次显示的标题。我不知道您使用哪个库进行数据库访问,因此您访问列/行的方式的细节会略有不同,但这里是伪代码:
$lastHeading = '';
foreach($rows as $row)
{
if ($lastHeading != $row['Description'])
{
if ($lastHeading != '')
echo '</ul>';
$lastHeading = $row['Description'];
echo "<h1>$lastHeading</h1>";
echo '<ul>';
}
echo '<li>'.$row['Text'].'</li>';
}
if ($lastHeading != '')
echo '</ul>';
这具有将评论放在<ul>
中的附加功能,不确定您是否需要这些评论。
这是有效的,因为您已按“说明”列进行排序。这意味着您知道具有相同“描述”的所有行将组合在一起。
答案 2 :(得分:0)
您可以为每个部分创建多个查询,也可以多次循环数据,并使用php根据描述类型进行过滤。
$descriptions = array('Content needs updating','Difficulty in navigating/finding content');
$rows = <fetch all rows from the query>;
foreach($descriptions as $description)
{
echo '<h1>',$description,'</h1>';
foreach($rows as $row)
{
if ($row['description'] == $description)
{
echo $row['text'],'<br />';
}
}
}