我每周使用以下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];
}
有效。但是,是否有更好(即更干净,更快)的方法来达到相同的结果?循环真的必要吗?谢谢。
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