我有像这样的PHP数组
Array (
[0] => Array (
[date] => 21/06/2014
[total_booking] => 1
)
[1] => Array (
[date] => 21/06/2014
[total_booking] => 1
)
[2] => Array (
[date] => 22/06/2014
[total_booking] => 2
)
)
我想要做的是我想删除重复的日期,并将删除日期的total_booking添加到一个唯一的日期。 例如:
2014年6月21日,我在一个实例中预订了1次,在其他情况下预订了2次。 现在我想添加所有预订,在本案例中为21日于2014年6月21日。
以下是我的代码:
$booking_total=0;
$trend_array=array();
$do_not_duplicate=array();
foreach($EM_Bookings as $EM_Booking){
$booking_date = date_i18n(get_option('dbem_date_format'), $EM_Booking->timestamp);
$booking_total = $EM_Booking->get_spaces();
$do_not_duplicate[]=$booking_date;
if (in_array($booking_date, $do_not_duplicate)) {
$do_not_duplicate[]=$booking_date;
$booking_array=array('date' =>$booking_date,'total_booking'=>$booking_total);
array_push($trend_array,$booking_array);
}else{
// i want to add $booking_total to corresponding date
}
}
答案 0 :(得分:1)
基本上,您想要每天预订的次数,不是吗?
$data = array([...]);
$days = array();
foreach($data as $day => $num) {
if(!isset($days[$day])) {
$days[$day] = 0;
}
$days[$day] += $num;
}
这是你想要的吗?
答案 1 :(得分:1)
我会创建一个用日期索引的新数组,然后重新创建你的数组:
$newarray = array () ;
foreach ($EM_Bookings as $EM_Booking) {
$booking_date = date_i18n(get_option('dbem_date_format'), $EM_Booking->timestamp);
$booking_total = $EM_Booking->get_spaces();
if (array_key_exists($booking_date, $newarray)) {
$newarray[$booking_date] += $booking_total ; // Add to existing array
}
else {
$newarray[$booking_date] = $booking_total ; // Create new
}
}
在这里,newarray
看起来像是:
Array (
[21/06/2014] => 2,
[22/06/2014] => 2
)
因此您可以轻松创建所需的数组,如下所示:
$finalarray = array () ;
foreach ($newarray as $date => $booking) {
$finalarray[] = array(
'date' => $date,
'total_booking' => $booking
) ;
}
答案 2 :(得分:1)
$unique = array();
foreach($EM_Bookings as $booking){
$date = $booking['date'];
if(!key_exists($date, $unique)){
$unique[$date] = $booking['total_booking'];
}else{
$unique[$date] += $booking['total_booking'];
}
}
/*
print_r($unique);
Array
(
[21/06/2014] => 2
[22/06/2014] => 2
)
*/