List records grouped by category name

前端 未结 2 639
-上瘾入骨i
-上瘾入骨i 2021-01-22 14:12

I am having some problems, trying to get data from my database, and show it correctly. I have a layout, where I have two \"lists\", where I can add rows to each lists. I can add

相关标签:
2条回答
  • 2021-01-22 14:44

    If you run a SQL query and you want the results in a particular order, then ALWAYS include an order by clause.

    In your case, you seem to want:

    SELECT dl.id, dl.list_id, dl.date, dl.list_name,
           dls.*
    FROM driving_lists dl LEFT JOIN
         driving_list_shipments dls
         ON dl.list_id = dls.list_id
    ORDER BY dl.list_id;
    

    I assume that list_id is what you mean by list_id.

    I should note that you have list_id appearing twice in the SELECT, because it is in both tables. You should probably explicitly list the columns you want from both tables, and avoid redundant columns.

    0 讨论(0)
  • 2021-01-22 14:48

    Luckily you are using PDO which already has this functionality for you, that can do exactly what you want - group the data based on some column.

    PDO can group results into the nested arrays, based on the first field selected. So you need to list your list id as the first field in the field list , and then get your rows using fetchAll() with aforementioned fetch mode:

    $sql = "SELECT dl.list_id, dl.id, dl.date, dl.list_name, dls.*
      FROM driving_lists dl LEFT JOIN
         driving_list_shipments dls
     ON dl.list_id = dls.list_id
     ORDER BY dl.list_id";
    
    $driving = $dbh->query($sql)->fetchAll(PDO::FETCH_GROUP);
    

    and now you get a neat nested array where your rows are grouped by list id!

    To make it output neatly you have to use two nested foreach operators

    foreach ($driving as $list_id => $list_data)
    {
         echo $list_data[0]['list_name']."<br />\n"; 
         foreach ($list_data as $row)
         {
             echo "whatever";
         }
    }
    
    0 讨论(0)
提交回复
热议问题