我需要获得前一周的第一个和最后一个日期。我使用下面的代码,它工作正常UNTIL我尝试读取循环外的变量。
<?php
$current_week = date(W);
$previous_week = $current_week - 1;
$year = date(o);
for($day=1; $day<=7; $day++) {
$temp = array ($day => date('Y-m-d', strtotime($year."W".$previous_week.$day)) . ' 00:00:00');
$firstday = $temp[1];
// echo here works fine
echo $firstday;
}
// echo here doesnt work anymore
echo $firstday;
?>
我真的不知道为什么这不起作用。我已经阅读了PHP文档,一切都告诉我它应该工作..我根本没有wizz,我现在真的很困惑。任何人都可以对此有所了解吗?
提前致谢!
答案 0 :(得分:0)
您在循环的后续迭代中覆盖$firstday
变量,因此最后它包含null
。
如果您启用错误报告,则会在访问$i > 1
$temp[1]
的迭代生成通知
您应该始终在开发和学习时启用错误报告,并且您应该(或者更好地)在发布代码之前解决所有警告。
以下是您的脚本中警告,error_reporting设置为E_ALL
:
> php /tmp/foo.php 2>&1 | grep Notice
PHP Notice: Use of undefined constant W - assumed 'W' in /private/tmp/foo.php on line 3
Notice: Use of undefined constant W - assumed 'W' in /private/tmp/foo.php on line 3
PHP Notice: Use of undefined constant o - assumed 'o' in /private/tmp/foo.php on line 5
Notice: Use of undefined constant o - assumed 'o' in /private/tmp/foo.php on line 5
2011-09-12 00:00:00PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
PHP Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
Notice: Undefined offset: 1 in /private/tmp/foo.php on line 8
答案 1 :(得分:0)
$ firstDay正在被重复使用和覆盖:
<?php
$current_week = date(W);
$previous_week = $current_week - 1;
$year = date(o);
for($day=1; $day<=7; $day++) {
$temp = array ($day => date('Y-m-d', strtotime($year."W".$previous_week.$day)) . ' 00:00:00');
$firstday = $temp[1];
// echo here works fine
echo "Inloop - ".$firstday."\n";
}
// echo here doesnt work anymore
echo "After loop - ".$firstday."\n";
?>
Results:
Inloop - 2011-09-12 00:00:00
Inloop -
Inloop -
Inloop -
Inloop -
Inloop -
Inloop -
After loop -
希望这有帮助