List records grouped by category name

前端 未结 2 665
-上瘾入骨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: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']."
    \n"; foreach ($list_data as $row) { echo "whatever"; } }

提交回复
热议问题