【发布时间】:2020-02-23 20:11:12
【问题描述】:
我每周使用以下 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')];
我认为这是一个更好的解决方案(满足我的需要)。
【问题讨论】:
-
完全可读的方法。
-
再次询问,为什么不直接使用
date('W'),获取当前 ISO-8601 周数?
标签: php foreach associative-array