<?php
$appointments = [
["appointment_date" => "2024-10-02", "appointment_time" => "10:00:00"],
["appointment_date" => "2024-10-02", "appointment_time" => "11:00:00"],
["appointment_date" => "2024-10-03", "appointment_time" => "14:00:00"],
["appointment_date" => "2024-10-02", "appointment_time" => "15:00:00"]
];
$combinedAppointments = [];
foreach ($appointments as $appointment) {
$date = $appointment['appointment_date'];
$time = $appointment['appointment_time'];
// 检查日期是否已存在于结果数组中
if (!isset($combinedAppointments[$date])) {
// 如果不存在,则初始化日期对应的数组
$combinedAppointments[$date] = ['appointment_date' => $date, 'appointment_times' => [$time]];
} else {
// 如果存在,则向appointment_times数组中添加时间
$combinedAppointments[$date]['appointment_times'][] = $time;
}
}
// 将appointment_times数组的值用逗号连接成一个字符串
foreach ($combinedAppointments as &$appointment) {
$appointment['appointment_times'] = implode(',', $appointment['appointment_times']);
}
// 如果你想要一个索引数组而不是关联数组,可以转换它
$indexedAppointments = array_values($combinedAppointments);
// 打印结果
print_r($indexedAppointments);
?>
Array
(
[0] => Array
(
[appointment_date] => 2024-10-02
[appointment_times] => 10:00:00,11:00:00,15:00:00
)
[1] => Array
(
[appointment_date] => 2024-10-03
[appointment_times] => 14:00:00
)
)
php 二维数组 二个元素相同的组合一个数组,不相同的组成另一个元素
最新推荐文章于 2024-10-10 12:45:21 发布