each():数组指针没有';工作不正常


each(): array pointer doesn't work properly

请考虑此代码

var_export ($dates);
while (list($key, $date) = each($dates))
{
    echo("current = ".current($dates));
    echo("key = " . key($dates));
}

结果是

Array
(
    [1359928800] => 1359928800
)
current =
key = 

我以为它应该返回1359928800,哪里错了?

在处理数组时,有一种不同的、不那么陈旧的结构用于处理迭代:foreach(此处为文档)。

我建议以这种方式对数组进行迭代。它更容易阅读,几乎不可能出错。此外,您不必担心在这里的小心中提到的无限循环中结束的可能性。

<?php
var_export($dates);
foreach($dates as $key => $value) {
    echo("current = ".$value);
    echo("key = ".$key);
}

为什么不使用$key$date

while (list($key, $date) = each($dates))
{
    echo("current = ".$date); // 1359928800
    echo("key = " . $key); // 1359928800
}

原因each已经推进了指针。

文件说明:

从数组中返回当前键和值对,并移动数组光标。

因此,在循环内部current引用下一个元素。在您的情况下,没有下一个元素,所以它是false。您应该使用$key$date或更好,使用foreach,就像已经建议的那样。