php - foreach 循环中的最后一项是它正在遍历的数组

标签 php arrays foreach output

我有一个包含本周、下周和下周日期的数组,其中包含日期、开始时间和结束时间。由于某种原因,当 foreach 循环到达最终日期时,它输出最后一周的数组而不是最终日期。这是数组的开始:

$dates = Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => "Mon 23rd June"
                    [1] => "9:00am"
                    [2] => "7:00pm"
                )

            [1] => Array
                (
                    [0] => "Tue 24th June"
                    [1] => "9:00am"
                    [2] => "7:00pm"
                )
            ...
    [1] => Array
        (

            [0] => Array
                (
                    [0] => "Mon 30th June"
                    [1] => "9:00am"
                    [2] => "7:00pm"
                )

            [1] => Array
                (
                    [0] => "Tue 1st July"
                    [1] => "9:00am"
                    [2] => "7:00pm"
                )
            ...

数组没有问题,因为我已经打印出来了。下面是foreach循环(错误发生的地方是嵌套的foreach($week as $day)):

foreach($dates as $week)
{ 
    if($i == 2)
    {
        $html .= '<table cellpadding="5" cellspacing="2" border="0" class="kc_ot_openingTable last">';
    }
    else
    {
        $html .= '<table cellpadding="5" cellspacing="2" border="0" class="kc_ot_openingTable">';
    }
    $html.= '<tr class="kc_ot_weekCommence">
        <td colspan="3">Week Commencing '.$week[0][0].'</td>
    </tr>
    <tr class="kc_ot_openingTableTitle">
        <td class="day">Day</td>
        <td class="open">Open</td>
        <td class="closed">Closed</td>
    </tr>';

    foreach($week as $day)
    {
        $html .= '<tr>
        <td>'.$day[0].'</td>
        <td class="open">'.$day[1].'</td>
        <td class="closed">'.$day[2].'</td>
    </tr>
    <tr>';
    }
    $html .= '</table>';
    ++$i;
}

谁能看出发生了什么事?

编辑

我发现 $dates 没问题,当 foreach($dates as $week) 循环在上周运行时出现问题。

重新编辑

这是这个函数的来源。请不要评判,我继承了这个网站:P

function getOpeningHours() {

date_default_timezone_set('Europe/London');
$dates = array(
    array(
        array(
            date("D jS F", strtotime("monday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("tuesday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("wednesday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("thursday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("friday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("saturday this week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("sunday this week")),
            "9:00am",
            "7:00pm"
        ),
    ),
    array(
        array(
            date("D jS F", strtotime("monday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("tuesday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("wednesday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("thursday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("friday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("saturday next week")),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("sunday next week")),
            "9:00am",
            "7:00pm"
        ),
    ),
    array(
        array(
            date("D jS F", strtotime("monday next week", strtotime("monday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("tuesday next week", strtotime("tuesday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("wednesday next week", strtotime("wednesday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("thursday next week", strtotime("thursday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("friday next week", strtotime("friday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("saturday next week", strtotime("saturday next week"))),
            "9:00am",
            "7:00pm"
        ),
        array(
            date("D jS F", strtotime("sunday this week", strtotime("sunday next week"))),
            "9:00am",
            "7:00pm"
        )
    ),
);

$sql[0] = "SELECT * FROM `tbl_opening_exceptions` WHERE `exception_date`  >= '".date("Y-m-d", strtotime("monday this week"))."' AND `exception_date` <= '".date("Y-m-d", strtotime("sunday this week"))."'";
$sql[1] = "SELECT * FROM `tbl_opening_exceptions` WHERE `exception_date`  >= '".date("Y-m-d", strtotime("monday next week"))."' AND `exception_date` <= '".date("Y-m-d", strtotime("sunday next week"))."'";
$sql[2] = "SELECT * FROM `tbl_opening_exceptions` WHERE `exception_date`  >= '".date("Y-m-d", strtotime("monday next week", strtotime("monday next week")))."' AND `exception_date` <= '".date("Y-m-d", strtotime("sunday next week", strtotime("sunday next week")))."'";
$i=0;
foreach($sql as $string)
{
    $result = mysql_query($string) or die(mysql_error());
    $r = mysql_fetch_array($result);

    foreach($dates[$i] as &$week)
    {
        if($week[0] == date("D jS F", strtotime($r["exception_date"])))
        {
            $week[1] =  date("g:ia", strtotime($r["exception_opening"]));
            $week[2] = date("g:ia", strtotime($r["exception_closing"]));
        }
    }
    ++$i;
}
$html = "";
$i = 0;
//print_r($dates);
foreach($dates as $week)
{ 
print_r($week);
    if($i == 2)
    {
        $html .= '<table cellpadding="5" cellspacing="2" border="0" class="kc_ot_openingTable last">';
    }
    else
    {
        $html .= '<table cellpadding="5" cellspacing="2" border="0" class="kc_ot_openingTable">';
    }
    $html.= '<tr class="kc_ot_weekCommence">
        <td colspan="3">Week Commencing '.$week[0][0].'</td>
    </tr>
    <tr class="kc_ot_openingTableTitle">
        <td class="day">Day</td>
        <td class="open">Open</td>
        <td class="closed">Closed</td>
    </tr>';

    foreach($week as $day)
    {
        $html .= '<tr>
        <td>'.$day[0].'</td>
        <td class="open">'.$day[1].'</td>
        <td class="closed">'.$day[2].'</td>
        </tr>';
    }
    $html .= '</table>';
    ++$i;
}
return $html;
}

最佳答案

TL;DR - 引用是邪恶的!

问题出在这里:

foreach ($dates[$i] as &$week) {
    // updates based on database values
}

foreach ($dates as $week) {
    // generate html from week data
}

在第一个循环结束后,最后一周仍然是一个引用,$dates[count($dates) - 1] 也是如此。在第二个循环中,$week 依次分配给 $dates 的每个元素。

当到达最后一个元素时,$week 被分配给它自己,因此创建了一个递归结构。

修复很简单:

foreach ($dates[$i] as &$week) {
    // updates based on database values
}
unset($week); // remove the reference

或者:

foreach ($dates[$i] as $week) {
    // updates based on database values
    if (<some condition>) {
        $dates[$i][1] = 'foo';
        $dates[$i][2] = 'bar';
    }
}

关于php - foreach 循环中的最后一项是它正在遍历的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24462394/

相关文章:

java - byte[]数组的长度

php - PDO - 对多个 foreach 循环使用相同的查询

linux - 运行 tcsh 脚本时出现“ undefined variable ”错误

php - Laravel 支持 return Redirect::back()->withFile() 吗?

php - PDO 库是否比原生 MySQL 函数更快?

javascript - 如何更新 Angular 数组中的现有项(已在外部更改)?

python - Python for循环简单数组

r - 如何处理 foreach 循环 R 中的 API 错误?

php - 使用 INFORMATION_SCHEMA 作为根,错误说它不存在?

php - 如何从PDO PHP 中的prepare() 获取查询错误?