循环索引数组

时间:2014-01-19 14:38:44

标签: php

我正在创建我的小预订系统,我正在尝试设置当前周的日期。 有人可以解释为什么下面的代码不起作用?

$lastWeek = [];
$arrlength=count($lastWeek);
$lastWeek[0] = date('D',strtotime('last monday'));
$lastWeek[1] = date('D',strtotime('last monday +1day'));
$lastWeek[2] = date('D',strtotime('last monday +2day'));
$lastWeek[3] = date('D',strtotime('last monday +3day'));
$lastWeek[4] = date('D',strtotime('last monday +4day'));

echo "<html><head><title>Event Booking timetable</title></head>";
echo "<body><table id=myTable border=2>";
echo "<tr><td>Week Commencing</td>";

for ($x=0; $x<$arrlength; $x++)
{
echo "<td>";
echo $lastWeek[$x];
echo "</td></tr>";
}

3 个答案:

答案 0 :(得分:2)

// declare vars
$lastWeek  = array();
$arrlength = 0;

// set vars
$lastWeek[0] = date('D',strtotime('last monday'));
$lastWeek[1] = date('D',strtotime('last monday +1day'));
$lastWeek[2] = date('D',strtotime('last monday +2day'));
$lastWeek[3] = date('D',strtotime('last monday +3day'));
$lastWeek[4] = date('D',strtotime('last monday +4day'));

$arrlength = count($lastWeek); // count after set $lastWeek!

// Print result
echo "<html><head><title>Event Booking timetable</title></head>";
echo "<body><table id=myTable border=2>";
echo "<tr><td>Week Commencing</td>";

for ($x=0; $x<$arrlength; $x++)
{
    echo "<td>";
    echo $lastWeek[$x];
    echo "</td></tr>";
}

答案 1 :(得分:2)

$arrlength=count($lastWeek);

必须在添加项目后设置,否则它将为0

答案 2 :(得分:2)

在填充数组之前,您需要计算数组的长度。而且,你没有以正确的方式关闭你的桌子和行。这应该有效:

$lastWeek = [];
$lastWeek[0] = date('D',strtotime('last monday'));
$lastWeek[1] = date('D',strtotime('last monday +1day'));
$lastWeek[2] = date('D',strtotime('last monday +2day'));
$lastWeek[3] = date('D',strtotime('last monday +3day'));
$lastWeek[4] = date('D',strtotime('last monday +4day'));
$arrlength = count($lastWeek);

echo "<html><head><title>Event Booking timetable</title></head>";
echo "<body><table id=myTable border=2>";
echo "<tr><td>Week Commencing</td></tr>";

for ($x=0; $x<$arrlength; $x++)
{
echo "<tr><td>";
echo $lastWeek[$x];
echo "</td></tr>";
}

echo "</table>";