【问题标题】:On a Day Like Today program像今天一样的一天节目
【发布时间】:2011-10-01 13:17:06
【问题描述】:

我编写了一个程序来查找当前日期,然后在 php 数组中进行搜索,并显示在今天这样的一天会发生什么。唯一的问题是程序无法正确读取 10-12 月份。这是我的代码:

php 数组:

$anniversary = array(
   '1/01' => array (
       '1813' => 'something here',
       '1824' => 'something here',
       '2001' => 'something here'
    ),
    '31/12' => array(
       '-450' => 'something here',
       '-168' => 'something here',
       '1942' => 'something here'
    )
);

程序是:

<?php
include 'array.php';
$today = date('d/m');

foreach ($anniversary[$today] as $hdate => $event) {
    $table[0][] = $hdate;
    $table[0][] = $event;
    $counter++;
}

do {
    $random = rand(0, $counter * 3);
} while($random % 2 == 0);

echo '<h2>'.$table[0][$random-1].": ".'</h2>'.
     '<p>'.$table[0][$random].'</p>';
?>

问题是 01-09 月份发现并正确显示,而 10-12 月份无法找到,因为将月份与日期混淆了。 有什么解决办法吗?

【问题讨论】:

  • d 是“带前导零的天数” - 为什么使用 '1/01' 而不是 '01/01'
  • 另外,为什么不使用另一个数组级别来分隔月和日呢?那么$anniversary[month][day][year] 什么的?
  • 为您修复了缩进。
  • 在处理日期/时间时始终使用时间戳或任何其他规范化格式。不会有更多的混乱,并且您将拥有大量内置的 php 函数来使用这种格式。不要重新发明方轮。

标签: php arrays date date-comparison


【解决方案1】:

除了你,没有什么会变得“困惑”。 :)

其实问题不是几个月,而是几天。您的数组的日期格式是 j/m(日期没有前导零,月份没有前导零),但您正在使用 d/m(日期前导零,月份没有前导零)进行查找。

When I fix your date format, the program works well.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2021-08-24
    • 2020-04-03
    • 1970-01-01
    相关资源
    最近更新 更多