2 回答

TA貢獻(xiàn)1811條經(jīng)驗 獲得超4個贊
因為您正在比較Ymd格式的日期,所以不需要日期/時間函數(shù)-換句話說,只需將日期視為字符串即可。
同時迭代開始和結(jié)束元素。當(dāng)您找到正確的范圍時,請存儲數(shù)據(jù)并繼續(xù)進(jìn)行下一個評估日期。
代碼:(演示)
$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貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
您可以在主日期變量中循環(huán)使用開始日期和結(jié)束日期數(shù)組的時間段,
// 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 —通過使用一個數(shù)組作為鍵并使用另一個數(shù)組作為其值來創(chuàng)建數(shù)組
array_walk —將用戶提供的函數(shù)應(yīng)用于數(shù)組的每個成員
array_search —搜索數(shù)組以獲取給定值,如果成功則返回第一個對應(yīng)的鍵
輸出
Array
(
[2011-04-11] => 10
[2011-06-28] => 10
[2011-09-26] => 20
[2012-01-02] => 30
[2012-05-12] => 30
)
演示。
- 2 回答
- 0 關(guān)注
- 203 瀏覽
添加回答
舉報