PHP & MYSQL: using group by for categories

前端 未结 6 712
栀梦
栀梦 2020-12-08 08:54

My database has the following setup

productid | productname | category id

and I want to output them like so:

category #1
it         


        
6条回答
  •  伪装坚强ぢ
    2020-12-08 09:50

    This should work:

    $categories = array();
    $result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
    while($row = mysql_fetch_assoc($result)){
        $categories[$row['category_id']][] = $row['product_name'];
    }
    
    // any type of outout you like
    foreach($categories as $key => $category){
        echo $key.'
    '; foreach($category as $item){ echo $item.'
    '; } }

    The output you can style yourself. You simply add everything into a multidimensional array with the category id as the first level keys.

    EDIT: The resulting array might look like this:

    $categories = array(
        'cateogy_id_1' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        'cateogy_id_2' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        ....
    );
    

提交回复
热议问题