Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

php - List records grouped by category name

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 multiple rows to each list.

I want to display the output, so the first list, along with all it's row is showed first and then the second list, along with it's rows.

Currently, it is showed like this:

    LIST #1
 -- row inside list #1 -- 
 -- row inside list #1 --

    LIST #2
 -- row inside list #2 --

Currently, it is displaying like this:

    LIST #1
 -- row inside list #1 -- 
    LIST #2
 -- row inside list #2 --
    LIST #1
 -- row inside list #1 --

Below is a visual:

Problem visualized

This is my selection in PHP:

    $driving=$dbh->prepare("SELECT 
    driving_lists.id,
    driving_lists.list_id,
    driving_lists.date,
    driving_lists.list_name,
    driving_list_shipments.*
FROM
    driving_lists
        LEFT JOIN driving_list_shipments ON driving_lists.list_id = driving_list_shipments.list_id

    ");
    $driving->execute();

And the output script:

foreach( $driving as $row){
                echo "<pre>";
                echo $row["list_name"];
                echo "<br />";
                echo $row["reference"];
                echo "</pre>";
        }

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 />
"; 
     foreach ($list_data as $row)
     {
         echo "whatever";
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...