php - MySQL 和 PHP - 每个?

标签 php mysql loops foreach

我有以下代码:

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 循环,但我很难理解这个问题 - 非常非常欢迎任何想法和建议!

谢谢,

最佳答案

简单方法

  1. 设置prev_descNULL
  2. 对于每一行打印text
  3. 如果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/

相关文章:

javascript - 多个div addClass和增量后缀

php - 无法使用php向mysql插入数据

javascript - PHP邮件函数发出电子邮件,但AJAX函数出错

mysql - 查询连接表上的计数不显示零计数结果

php - 插入数据mysql数据库时出错,

c - fopen 用于读取/写入文件夹 C 中的多个文件

windows - 循环遍历 .bat 中的行并存储变量而不覆盖

php - htaccess 带有 .php 的旧文件 没有 php 的新文件

php - nginx php-fpm 配置达到 child 限制

mysql - 查找重复的电话号码(即使格式不同)