php 二维数组 二个元素相同的组合一个数组,不相同的组成另一个元素

<?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  
        )  
  
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值