使用php从MySql显示此数据的更好方法

时间:2013-05-15 06:05:19

标签: php mysql

我目前在表格中有这样的数据:

id  |  type
------------
1   |  1
2   |  1
3   |  2
4   |  2
5   |  3
6   |  3
6   |  3

我需要显示如下数据:

Type 1
--All type ones go here
Type 2
-- All type twos go here
Type 3
All type threes go here

我现在的方法是使用两个独立的sql语句和循环。

select distinct type as type from table
while()
{
 select type from table where type = type;
 while()
 {

 }
}

有没有更好的方法来做到这一点并获得我想要的结果,或者只使用两个循环?

3 个答案:

答案 0 :(得分:3)

  1. 更改您的查询,以便您使用ORDER BY type ASC
  2. 遍历结果,构建一个关联数组,其中键是类型,值是ids。
  3. 现在您只有一个循环,并且可以通过关联数组中的类型访问ID。通过键遍历数组应该是微不足道的,然后显示该键的所有ID。

答案 1 :(得分:1)

GROUP_CONCAT()使用GROUP BY

SELECT
    `type`,
    GROUP_CONCAT(`id` SEPARATOR ',') as `ids`
FROM
    `table`
GROUP BY
    `type`
ORDER BY
    `type`;

在每个周期迭代中,$row['ids']可能是explode() d,如:

<?php

while($row = $result->fetch_assoc()){
    $ids = explode(',', $row['ids']);

    echo 'Type ', $row['type'], PHP_EOL;

    if(empty($ids))continue;

    foreach($ids as $id){
        echo $id, ' ';
    }

    echo PHP_EOL;
}

?>

答案 2 :(得分:1)

只需选择所有内容,并在每次点击新类型时进行检查。这允许您仅使用一个查询在O(n)时间内列出所有内容。

$result = mysql_query('SELECT id, type FROM table ORDER BY type ASC');
$type = 0;
while ($row = mysql_fetch_assoc($result) {
  if ($type != $row['type']) {
    // New type found
    $type = $row['type'];
    echo "Type " + $row['type'] + "\n";
  } 
  echo "-- " + $row['id'] + "\n";
}

这会给你一个这样的输出

Type 1
-- 1
-- 2
Type 2
-- 3
-- 4
Type 3
-- 5
-- 6
-- 7
相关问题