PHP - 按日期范围获取关联数组值,无需循环
PHP - Get associative array value by date range without loop
我使用以下 PHP 代码每周显示不同的文本(只有一个):
<?php
$items = [
[
'start' => '2020-02-03',
'end' => '2020-02-09',
'html' => 'Text #1'
],
[
'start' => '2020-02-10',
'end' => '2020-02-16',
'html' => 'Text #2'
],
[
'start' => '2020-02-17',
'end' => '2020-02-23',
'html' => 'Text #3'
],
];
$currentDate = date('Y-m-d');
foreach ($items as $item) {
if ($currentDate >= $item[start] && $currentDate <= $item[end]) echo $item[html];
}
有效。
但是是否有更好(即更清洁、更快)的方法来实现相同的结果?循环真的有必要吗?
谢谢
更新
受 Progrock 的回答(我感谢)的启发,我将修改我的代码如下:
$items =
[
'06' => 'Text #1',
'07' => 'Text #2',
'08' => 'Text #3',
'09' => 'Text #4'
];
$date = new DateTime(date('Y-m-d'));
echo $items[$date->format('W')];
我认为这是一个更好的解决方案(满足我的需要)。
https://www.php.net/manual/en/function.array-filter.php
$currentDate = date('Y-m-d');
$filteredItems = array_filter($items, function($item) use ($currentDate) {
return $currentDate >= $item['start'] && $currentDate <= $item['end'];
});
尽管如此,您最终仍将不得不循环过滤的项目以进行输出。
由于您的范围是星期一->星期日,您可以使用 ISO-8601 周编号。尽管这里的数据在没有评论的情况下更难解释。
<?php
$items =
[
'06' => 'Text #1',
'07' => 'Text #2',
'08' => 'Text #3'
];
$iso_week = date('W', strtotime('2020-02-12'));
echo $items[$iso_week];
输出:
Text #2
我使用以下 PHP 代码每周显示不同的文本(只有一个):
<?php
$items = [
[
'start' => '2020-02-03',
'end' => '2020-02-09',
'html' => 'Text #1'
],
[
'start' => '2020-02-10',
'end' => '2020-02-16',
'html' => 'Text #2'
],
[
'start' => '2020-02-17',
'end' => '2020-02-23',
'html' => 'Text #3'
],
];
$currentDate = date('Y-m-d');
foreach ($items as $item) {
if ($currentDate >= $item[start] && $currentDate <= $item[end]) echo $item[html];
}
有效。 但是是否有更好(即更清洁、更快)的方法来实现相同的结果?循环真的有必要吗? 谢谢
更新
受 Progrock 的回答(我感谢)的启发,我将修改我的代码如下:
$items =
[
'06' => 'Text #1',
'07' => 'Text #2',
'08' => 'Text #3',
'09' => 'Text #4'
];
$date = new DateTime(date('Y-m-d'));
echo $items[$date->format('W')];
我认为这是一个更好的解决方案(满足我的需要)。
https://www.php.net/manual/en/function.array-filter.php
$currentDate = date('Y-m-d');
$filteredItems = array_filter($items, function($item) use ($currentDate) {
return $currentDate >= $item['start'] && $currentDate <= $item['end'];
});
尽管如此,您最终仍将不得不循环过滤的项目以进行输出。
由于您的范围是星期一->星期日,您可以使用 ISO-8601 周编号。尽管这里的数据在没有评论的情况下更难解释。
<?php
$items =
[
'06' => 'Text #1',
'07' => 'Text #2',
'08' => 'Text #3'
];
$iso_week = date('W', strtotime('2020-02-12'));
echo $items[$iso_week];
输出:
Text #2