2 回答
TA贡献1811条经验 获得超4个赞
因为您正在比较Ymd格式的日期,所以不需要日期/时间函数-换句话说,只需将日期视为字符串即可。
同时迭代开始和结束元素。当您找到正确的范围时,请存储数据并继续进行下一个评估日期。
代码:(演示)
$dates = ['2011-04-11', '2011-06-28', '2011-09-26', '2012-01-02', '2012-05-12'];
$startdates = [
10 => '2011-01-01',
20 => '2011-07-01',
30 => '2012-01-01',
40 => '2012-07-01'
];
$enddates = [
10 => '2011-06-30',
20 => '2011-12-31',
30 => '2012-06-30',
40 => '2012-12-31'
];
foreach ($dates as $date) {
foreach ($startdates as $key => $startdate) {
if ($date >= $startdate && $date <= $enddates[$key]) {
$result[$date] = $key;
continue 2;
}
}
$result[$date] = 'out of bounds';
}
var_export($result);
输出:
array (
'2011-04-11' => 10,
'2011-06-28' => 10,
'2011-09-26' => 20,
'2012-01-02' => 30,
'2012-05-12' => 30,
)
TA贡献1845条经验 获得超8个赞
您可以在主日期变量中循环使用开始日期和结束日期数组的时间段,
// combining keys and values
$temp = array_combine($startdates, $enddates);
$result = [];
// & for making changes on assigned address of variable regardless of array_walk function scope
array_walk($dates, function ($item, $key) use (&$result, $temp, $startdates) {
foreach ($temp as $k => $v) {
// comparing with start and end date range
if (strtotime($item) >= strtotime($k) && strtotime($item) <= strtotime($v)) {
// searching by value and getting key
$result[$item] = array_search($k, $startdates);
// if comes to this loop break as its never gonna come here
break;
}
}
});
array_combine —通过使用一个数组作为键并使用另一个数组作为其值来创建数组
array_walk —将用户提供的函数应用于数组的每个成员
array_search —搜索数组以获取给定值,如果成功则返回第一个对应的键
输出
Array
(
[2011-04-11] => 10
[2011-06-28] => 10
[2011-09-26] => 20
[2012-01-02] => 30
[2012-05-12] => 30
)
演示。
- 2 回答
- 0 关注
- 174 浏览
添加回答
举报