我有一個表,其中有 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
我使用 $this->db->get() 來檢索數據,我可以輕鬆循環。但由於每一行都在數組中,我發現很難將它們分組。我無法使用 mysql 群組,因為我需要每一行。 
舉個例子,我想顯示如下的項目
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
透過 air_id 將結果分組的最佳方法是什麼,以便我可以迭代
從資料庫取得資料:
$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();建立一個空數組來保存分組資料:
迭代取得的資料並按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; }現在,您已在 $grouped_data 陣列中按 air_id 分組了資料。您可以循環存取此數組以顯示您指定的資料:
foreach ($grouped_data as $air_id => $group) { echo "air_id - $air_id"; foreach ($group as $row) { echo $row['FlightDuration'] . ' ' . $row['out_or_in'] . ' ' . $row['flightduration2'] . '
'; } echo "
"; }
此程式碼將循環遍歷分組資料並按照您的描述進行顯示,每組航班資料都在對應的air_id下。