0

一旦我运行我的查询,将几列连接在一起,我得到这样的结果:

id     item     category
1      item 1   A
1      item 1   B
1      item 1   C
2      item 2   A
2      item 2   D
3      item 3   B
3      item 3   E

我有一个将输出每一行的while循环:。

while($results = mysql_fetch_array($raw_results)) {
    echo $results['item'].<br>;
    echo "Category: ".$results['category'];
}

它给出了这个:

<div>
Item 1
Category: A
</div>

<div>
Item 1
Category: B
</div>

依此类推,但我需要做的是将每个 ID 的所有值组合到一个空格中,因此结果如下所示:

<div>
Item 1
Category: A, B, C
</div>

<div>
Item 2
Category: A, D
</div>

<div>
Item 3
Category: B, E
</div>

最好的方法是什么?我应该用每个 ID 的行创建另一个数组,然后循环遍历它(以及我将如何设置数组?)或者还有别的东西吗?

4

5 回答 5

4

尝试GROUP BY_GROUP_CONCAT

http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/

于 2013-04-22T23:10:28.907 回答
1

您可以在查询中完成所有这些操作,而不是依赖 PHP。

  Select item, group_concat(category) FROM yourtable GROUP BY Item
于 2013-04-22T23:11:01.957 回答
1

我会做这样的事情:

select id, item, group_concat(category) from Table1
group by id, item

SQLFiddle

于 2013-04-22T23:12:33.223 回答
0

为每个项目创建一个类别数组:

while($results = mysql_fetch_array($raw_results)) {
    $items[$results['item']][] = $results['category'];
}

然后用它来输出你的 HTML:

foreach ($items as $itemName => $categories) {
    echo $itemName.'<br>';
    echo 'Categories: '.implode(', ',$categories);
}
于 2013-04-22T23:12:30.360 回答
0

If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function array_unique. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here is a link to the PHP manual on this function:

http://www.php.net/manual/en/function.array-unique.php

于 2013-04-22T23:13:26.130 回答