如果我们的客户服务联络中心关闭,我们需要能够在我们的网站上显示消息。我正在尝试清理代码,检查当天是否是假日。
过去我每个假期使用一个变量,每个假期使用一个if语句。这是很多代码,它看起来很草率和不专业。我一直在阅读多维数组,看起来这可能是一个可行的解决方案。
以下是我的数组示例:
//Store Holidays in multidimensional array
$holidays = array
(
"NewYearsDay"=>array
(
"Date"=>"01-01-2014",
"Closed"=>"Yes"
),
"MartinLutherKingJrDay"=>array
(
"Date"=>"01-21-2013,
"Closed"=>"Yes"
)
);
这给了我以下(这很好 - 这部分没问题)
Array
(
[NewYearsDay] => Array
(
[Date] => 01-01-2014
[Closed] => Yes
)
[MartinLutherKingJrDay] => Array
(
[Date] => 01-21-2013
[Closed] => Yes
)
)
但是,当我使用foreach
循环时,我只能获得假期的名称。我想得到日期和结束信息。
foreach ($holidays as $key => $value) {
echo $key;
只给我:
NewYearsDayMartinLutherKingJrDay
(我稍后可以处理的间距问题)
我希望最终能够做到这样的事情:
//loop through the array and do this for each iteration:
if ((NewYearsDay['date'] == date('d-m-Y')) && (NewYearsDay['closed'] == Yes)) {
$status = "closed";
}
答案 0 :(得分:4)
忽略$key
并使用$value
来覆盖您的数据。
foreach ($holidays as $value) {
var_dump($value);
if (($value['date'] == date('d-m-Y')) && ($value['closed'] == 'Yes')) {
$status = "closed";
}
}
答案 1 :(得分:2)
正如diegoperini上面提到的,这里有一个稍微有点文档的版本:
foreach ($holidays as $name => $value) {
// $name should be there, it contains your "MartinLutherKingDay" etc,
// could be handy.
// although I'd put the formatted display name into your array:
// $value['name'] = 'Martin Luther King Day';
list($date, $closed) = $value;
if ($date == date('d-m-Y')) && ($closed == 'Yes')) {
// if you find what you want, and you only want one, you can skip
// the rest of the foreach
$status = "closed";
continue;
}
}