我有一个像这样的数组:
$cakedays = array (
2019-06-27 = "Dave"
2019-07-09 = "Rob, James, Brian"
2019-07-16 = "Sam"
2019-07-17 = "Kate"
2019-07-23 = "Alex"
2019-07-24 = "Jen"
2019-07-25 = "Pete, Tong"
)
我想遍历这个数组,如果我连续发现两天,我想在第二天合并两个名字。但是只连续两天,而不是三天或更长时间。
所以结果数组看起来像这样
$cakedays = array (
2019-06-27 = "Dave"
2019-07-09 = "Rob, James, Brian"
2019-07-17 = "Sam, Kate"
2019-07-24 = "Alex, Jen"
2019-07-25 = "Pete, Tong"
)
这是我到目前为止的逻辑,但是当我连续三天击中它时,它就会崩溃。它的迟到和合理的逻辑现在让我不知所措。
$days = [];
$arr2 = [];
$i = 0;
foreach ($cakedays as $date => $values){
$days[] = $date;
$arr2[$date] = $values;
if($i !== 0){
$date1 = new DateTime($days[$i]);
$date2 = new DateTime($days[$i - 1]);
$diff = $date1->diff($date2);
$names = [];
if ($diff->days === 1) {
$names[] = $arr2[$date2->format('Y-m-d')];
$names[] = $arr2[$date1->format('Y-m-d')];
unset($arr2[$date2->format('Y-m-d')]);
$arr2[$date] = implode(", ", $names);
}
}
$i++;
}
答案 0 :(得分:1)
$array =
[
'2019-06-27' => 'Dave',
'2019-07-09' => 'Rob, James, Brian',
'2019-07-16' => 'Sam',
'2019-07-17' => 'Kate',
'2019-07-23' => 'Alex',
'2019-07-24' => 'Jen',
'2019-07-25' => 'Pete, Tong'
];
$ignore = [];
foreach ($array as $today => $names)
{
if (isset($ignore[$today]))
{
continue;
}
$tomorrow = date('Y-m-d', strtotime("$today +1 day"));
if (!isset($array[$tomorrow]))
{
continue;
}
$array[$tomorrow] = "$names, $array[$tomorrow]";
$ignore[$tomorrow] = true;
unset($array[$today]);
}