我有一个表,其中有 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粉0432953372024-04-07 16:23:46
从数据库中获取数据:
$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();
创建一个空数组来保存分组数据:
$grouped_data = 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下。