我有以下代码:
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 循环,但我很难理解这个问题 - 非常非常欢迎任何想法和建议!
谢谢,
最佳答案
简单方法
- 设置
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>
为了让行“分组”。否则这种简单的方法将行不通。
较少特定于演示文稿的方法
我可以被认为更“干净”来创建某种二维容器来“分类”提取的数据,例如,
$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()
.
关于php - MySQL 和 PHP - 每个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3904925/