依照ID對MySQL結果進行分組以便循環遍歷
P粉638343995
P粉638343995 2024-04-06 17:27:56
0
1
484

我有一個表,其中有 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 將結果分組的最佳方法是什麼,以便我可以迭代

P粉638343995
P粉638343995

全部回覆(1)
P粉043295337
  1. 從資料庫取得資料:

    $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. 建立一個空數組來保存分組資料:

    $grouped_data = array();
  3. 迭代取得的資料並按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. 現在,您已在 $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下。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!