简体   繁体   中英

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.

...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.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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