简体   繁体   English

使用带有ID字段的PHP将MySQL结果分组

[英]Grouping MySQL results with PHP with an ID field

I currently have a database setup with the following fields: 我目前有一个包含以下字段的数据库设置:

Category_Name | Display_Name | Display_ID

What I'm trying to do is to group everything by category, and then provide a hyperlink by display name, but I just can't seem to figure out what the heck I'm doing. 我想做的是按类别对所有内容进行分组,然后按显示名称提供超链接,但是我似乎无法弄清楚我在做什么。 For example: 例如:

Cars
   Jetta -> ID: 1
   Passat -> ID: 2
Trucks
   Yukon -> ID: 3
   Sierra -> ID: 4

So what I currently have, I can get the first heading and the next section, but for some reason I can't get the ID number to end up where I want it. 所以我目前所拥有的,我可以得到第一个标题和下一部分,但是由于某种原因,我无法获得ID号以所需的结尾。

...mysql to gather the data as an array
$categories = Array();
foreach( $cats as $permrow ) 
{
   $categories[$permrow['Category_Name']][] = $permrow['Display_Name'];
}

foreach($categories as $key => $category){
    echo '<h1>'.$key.'</h1><br/>';
    foreach($category as $key => $item){ 
        echo $item.'<br/>';
    }
}

So I get how this works, but I can't quite figure out what my next step is to get that third piece of data. 因此,我了解了它的工作原理,但是我无法弄清楚下一步要获取第三条数据是什么。

If the ID is unique you can add the id as the key of the array in the second dimension. 如果ID是唯一的,则可以在第二维中将ID添加为数组的键。

$categories = Array();
foreach( $cats as $permrow ) 
{  //--added ID as key to the 2nd array dimension
   $categories[$permrow['Category_Name']][$permrow['Display_ID']] = $permrow['Display_Name'];
}

foreach($categories as $key => $category){
    echo '<h1>'.$key.'</h1><br/>';
    foreach($category as $id => $item){ //--changed $key to $id
        echo "<a href=\"thelink?id=$id\">$item</a><br>";
    }
}

Live code: https://www.tehplayground.com/96etJ3UQAOi8oRYz 实时代码: https : //www.tehplayground.com/96etJ3UQAOi8oRYz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM