PHP-按日期范围获取关联数组值,不带循环

问题描述 投票:0回答: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];
}

有效。但是,是否有更好(即更干净,更快)的方法来达到相同的结果?循环真的必要吗?谢谢。

php foreach associative-array
2个回答
0
投票

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'];
});

尽管,最终仍然需要循环过滤的项以输出。


0
投票

由于您的范围是星期一->星期日,您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.