我有一个php数组如下:
Array
(
[0] => Array
(
[EmployeeAttendance] => Array
(
[attendance_id] => 1
[arrival_datetime] => 2016-11-01 03:31:00
[status] => Present
)
)
[1] => Array
(
[EmployeeAttendance] => Array
(
[attendance_id] => 2
[arrival_datetime] => 2016-11-03 06:31:00
[status] => Present
)
)
[2] => Array
(
[EmployeeAttendance] => Array
(
[attendance_id] => 3
[arrival_datetime] => 2016-11-06 07:31:00
[status] => Present
)
)
[3] => Array
(
[EmployeeAttendance] => Array
(
[attendance_id] => 4
[arrival_datetime] => 2016-11-08 19:31:00
[status] => Present
)
)
[4] => Array
(
[EmployeeAttendance] => Array
(
[attendance_id] =>5
[arrival_datetime] => 2016-11-10 08:00:00
[status] => Present
)
)
)
在这个数组中,我们可以看到从'2016-11-01'到'2016-11-10'的出勤详情,有些日期在这里缺失,如'2016-11-02','2016-11- 04','2016-11-05','2016-11-07'和'2016-11-09'。 现在我想查看“2016-11-01”到“2016-11-10”之间的日期缺失日期,并将缺少的日期插入到数组中,状态为“缺席”。请给出一些建议。
答案 0 :(得分:1)
首先收集所有日期,排序,生成第一个之间的日期范围,然后丢失插入
$data = [
[
'EmployeeAttendance' => [
'attendance_id'=>1
,'arrival_datetime'=>'2016-11-01 03:31:00'
,'status'=>'Present'
]
]
,[
'EmployeeAttendance' => [
'attendance_id'=>1
,'arrival_datetime'=>'2016-11-05 03:31:00'
,'status'=>'Present'
]
]
,[
'EmployeeAttendance' => [
'attendance_id'=>1
,'arrival_datetime'=>'2016-11-11 03:31:00'
,'status'=>'Present'
]
]
];
$dates = [];
foreach ($data as $x => $d) {
$dates[] = substr($d['EmployeeAttendance']['arrival_datetime'],0,10);
}
sort($dates);
$period = new DatePeriod(
new DateTime($dates[0]),
new DateInterval('P1D'),
new DateTime(end($dates))
);
foreach ($period as $d) {
$key = $d->format('Y-m-d');
if (!in_array($key,$dates)) {
$data[] = [
'EmployeeAttendance' => [
'arrival_datetime'=>$key
,'status'=>'absent'
]
];
}
}
print_r($data);
答案 1 :(得分:1)
您好,您也可以试试这个
$a = array(array('EmployeeAttendance'=>array('attendance_id'=>1,'arrival_datetime'=>'2016-11-01 03:31:00','status'=>'Present')),array('EmployeeAttendance'=>array('attendance_id'=>2,'arrival_datetime'=>'2016-11-03 04:31:00','status'=>'Present')),array('EmployeeAttendance'=>array('attendance_id'=>3,'arrival_datetime'=>'2016-11-07 07:31:00','status'=>'Present')),array('EmployeeAttendance'=>array('attendance_id'=>4,'arrival_datetime'=>'2016-11-09 05:31:00','status'=>'Present')));
foreach($a as $key=>$data){
$presentDates[] = date("j", strtotime($data['EmployeeAttendance']['arrival_datetime']));// will give array of present dates array(1,3,7,9);
}
$first = reset($presentDates);
$last = end($presentDates);
$total = range($first,$last); // will give all dates between start and end
$absentArr = array_diff($total, $presentDates); // will give missing dates array(2,4,5,6,8)
foreach($absentArr as $value){
$a[]['EmployeeAttendance'] = array('arrival_datetime'=>'2016-11-'.$value,'status'=>'Absent');
}
print_r($a);