查询数据库后打印出部分唯一的数据


Printing out partially unique data after querying a db

我很难弄清楚如何像我需要的那样使用表数据……我的表由一个类别名称列(对于许多子类别具有相同的值)组成,另一列包含子类别名称。

例如:

col1        col2
------------------
apples      fruits
oranges     fruits
pears       fruits
honda       cars
volvo       cars
audi        cars

我正试图编写一个select语句,从数据库中选择所有数据,并只打印出一次类别名称,同时打印出该特定类别名称包含的所有子类别。

类似于:

水果:

  • 苹果
  • 橙子
  • 皮尔斯

汽车:

  • 本田
  • 沃尔沃
  • 奥迪
SELECT
    col2,
    GROUP_CONCAT(col1 SEPARATOR ',') as stuff
FROM table1
GROUP BY col2

如果要在名称前面加上"-",可以使用CONCAT('-',col1)而不是col1

此php代码将结果转换为一维数组

$conn = new mysqli('host','user','pass','db_name');
if ($conn->connect_errno) {
    printf("Connect failed: %s'n", $conn->connect_error);
    exit();
}
if (!($rs = $conn->query("
        SELECT
            col2,
            GROUP_CONCAT(col1 SEPARATOR ',') as stuff
        FROM table1
        GROUP BY col2
    "))) {
    printf("Error: %s'n", $conn->error);
    exit();
}

$result = array();
while ($row = $rs->fetch_object()){
    $result[] = $row->col2;
    if(!empty($row->stuff)) $result = array_merge($result,explode(',',$row->stuff));
}

它推荐给您什么。此外,这将使你的生活与阵列非常困难。考虑试试这样的东西:

$query = mysql_query("SELECT * FROM table");
$array = array();
while($row = mysql_fetch_assoc($query)) {
   $cat = $row['col2'];
   $item = $row['col1'];
   $array[$cat] = $item;
}

现在,您有了一个数组,其中类别作为键,项作为每个键的值。

祝你好运!