gpt4 book ai didi

group mysql results by id for looping(按ID对MySQL结果进行分组以进行循环)

转载 作者:bug小助手 更新时间:2023-10-25 11:20:28 25 4
gpt4 key购买 nike



I have a table that has flight data in mysql. Im writing a php code that will group and display the data in groups using codeigniter 3

我有一个表,其中包含MySQL中的航班数据。我正在编写一个php代码,它将使用codeigniter 3分组并显示数据。


 journey_id     air_id  FlightDuration  out_or_in   flightduration2
1 1 20hr 5min outbound 1205
2 1 20hr 5min outbound 1300
3 1 17hr 55min inbound 2258
4 1 17hr 55min inbound 1075
5 2 31hr 40min outbound 1970
6 2 31hr 40min outbound 1900
7 2 17hr 55min inbound 2223
8 2 17hr 55min inbound 1987
9 3 10hr 45min outbound 645
10 3 11hr 25min inbound 685

im using a $this->db->get() to retrieve the data and i can easily loop through. but since each row is in array im finding it difficult to group them. i cannot use the mysql group coz i need each row.

我正在使用$this->db->get()来检索数据,我可以轻松地遍历。但是因为每一行都在数组中,所以我发现很难对它们进行分组。我不能使用MySQL组,因为我需要每一行。


for an example i want to display the items as below

作为一个例子,我想显示如下项目


air_id - 1
20hr 5min outbound 1205
20hr 5min outbound 1300
17hr 55min inbound 2258
17hr 55min inbound 1075

air_id - 2
31hr 40min outbound 1970
31hr 40min outbound 1900
17hr 55min inbound 2223
17hr 55min inbound 1987

air_id - 3
10hr 45min outbound 645
11hr 25min inbound 685

what would be the best way to group the result by the air_id so i can iterate through

根据air_id对结果进行分组以便我可以遍历的最佳方式是什么


更多回答
优秀答案推荐


  1. Fetch the data from the database:


    $this->db->select('journey_id, air_id, FlightDuration, out_or_in, flightduration2');
    $this->db->from('your_table_name'); // Replace 'your_table_name' with the actual table name
    $query = $this->db->get();
    $data = $query->result_array();


  2. Create an empty array to hold the grouped data:


     $grouped_data = array();


  3. Iterate through the fetched data and group it by air_id:


    foreach ($data as $row) {

    $air_id = $row['air_id'];

    // Check if the air_id already exists in the grouped_data array
    if (!isset($grouped_data[$air_id])) {
    // If not, initialize an empty array for this air_id
    $grouped_data[$air_id] = array();
    }

    // Add the current row to the group for this air_id
    $grouped_data[$air_id][] = $row;
    }


  4. Now, you have the data grouped by air_id in the $grouped_data array. You can iterate through this array to display the data as you specified:


    foreach ($grouped_data as $air_id => $group) {
    echo "air_id - $air_id<br>";

    foreach ($group as $row) {
    echo $row['FlightDuration'] . ' ' . $row['out_or_in'] . ' ' . $row['flightduration2'] . '<br>';
    }

    echo "<br>";
    }



This code will loop through the grouped data and display it as you described, with each group of flight data under the corresponding air_id.

这段代码将遍历分组的数据并按照您的描述显示它,每组航班数据都在相应的air_id下。


更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com