我将日期存储在数组中,但是以特殊格式定义日期范围,如下所示:
Array
(
[0] => Array
(
[0] => Array ///date start
(
[0] => 2017
[1] => 10 //month
[2] => 3 //day
)
[1] => Array //date end
(
[0] => 2017
[1] => 10 //month
[2] => 5 //day
)
)
[1] => Array
(
[0] => Array //date start
(
[0] => 2017
[1] => 11
[2] => 23
)
[1] => Array //date end
(
[0] => 2017
[1] => 11
[2] => 25
)
)
)
如果数组中存在特定的字符串日期,我需要一个可以返回的函数
2017-10-01. is_in_array ('2017-10-01').
但我不明白如何处理foreach和日期范围的特殊数组格式。
答案 0 :(得分:1)
试试这个
$arr = array(
[
[2017,10,3],
[2017,10,5]
],
[
[2017,11,23],
[2017,11,25]
],
[
[2017,12,1],
[2017,12,10]
]
);
function is_in_array($array, $date) {
$timestamp = strtotime($date);
$date = date('d',$timestamp);
$month = date('m',$timestamp);
$year = date('Y',$timestamp);
foreach ($array as $key => $value) {
foreach($value as $value2) {
if($value2[0]==$year && $value2[1] == $month && $date == $value2[2])
return true;
}
}
return false;
}
此处is_in_array()
的第一个参数是您要查找日期的数组
第二个参数是您要查找的日期。
因此
is_in_array('2017-12-1'); //will return true
is_in_array('2017-5-2'); //will return false
答案 1 :(得分:0)
试试这个:
$rangesArr = [
[[2017, 10, 3], [2017, 10, 5]],
[[2017, 11, 23], [2017, 11, 25]],
];
function is_in_array ($date) {
global $rangesArr;
$dateUnix = strtotime($date);
foreach ($rangesArr as $range) {
$rangeStartUnix = strtotime("{$range[0][0]}-{$range[0][1]}-{$range[0][2]}");
$rangeEndUnix = strtotime("{$range[1][0]}-{$range[1][1]}-{$range[1][2]}");
if ($dateUnix >= $rangeStartUnix && $dateUnix < $rangeEndUnix) {
return true;
}
}
return false;
}
var_dump(is_in_array('2017-10-04')); // Returns true.
var_dump(is_in_array('2017-10-05')); // Returns false.
输出:
bool(true)
bool(false)
基本上,它只是遍历数组,将子范围的开始和结束数组转换为unix时间戳,并将其与传入日期的unix时间戳进行比较。
答案 2 :(得分:0)
如果您需要时间,可以尝试使用此变体
<?php
$discountDatesArr = [
[[2018, 8, 5, '00:00:00'], [2018, 8, 9, '23:59:59']],
[[2018, 8, 15, '00:00:00'], [2018, 8, 15, '23:59:59']],
[[2018, 8, 19, '00:00:00'], [2018, 8, 19, '23:59:59']],
[[2018, 8, 22, '00:00:00'], [2018, 8, 22, '23:59:59']],
[[2018, 8, 29, '00:00:00'], [2018, 8, 29, '23:59:59']],
];
$isDiscountSystemActive = false;
$dateUnix = strtotime(date("Y-n-j H:i:s"));
foreach ($discountDatesArr as $range) {
$rangeStartUnix = strtotime("{$range[0][0]}-{$range[0][1]}-{$range[0][2]} {$range[0][3]}");
$rangeEndUnix = strtotime("{$range[1][0]}-{$range[1][1]}-{$range[1][2]} {$range[1][3]}");
if ($dateUnix >= $rangeStartUnix && $dateUnix < $rangeEndUnix) {
$isDiscountSystemActive = true;
}
}
define ("ISDISCOUNTACTIVE", $isDiscountSystemActive);
echo ISDISCOUNTACTIVE;