我通过与一个foreach关联数组循环。我希望能够检查键值对正在处理的是最后,所以我可以给它特殊的待遇。任何想法如何,我可以做到这一点的最好方法是什么?

foreach ($kvarr as $key => $value){
   // I'd like to be able to check here if this key value pair is the last
   // so I can give it special treatment
}
有帮助吗?

解决方案

假设你不改变所述阵列,同时通过它迭代,可以认为,在循环递减计数器,并且一旦它达到0,则正在处理最后:

<?php
$counter = count($kvarr);
foreach ($kvarr as $key => $value)
{
    --$counter;
    if (!$counter)
    {
        // deal with the last element
    }
}
?>

其他提示

简单,因为这,不受柜台等“黑客”。

foreach ($array as $key => $value) {

   // your stuff

   if (next($array) === false) {
      // this is the last iteration
   }
}

请注意,必须使用===,因为函数next()可以返回其的计算结果为false 下,如0或“”(空字符串)非布尔值。

我们并不需要通过用foreach阵列来迭代,我们可以使用()的末尾,键()和电流()PHP函数到达的最后一个元素,并得到它的键+值。

<?php

$a = Array(
  "fruit" => "apple",
  "car" => "camaro",
  "computer" => "commodore"
);

// --- go to the last element of the array & get the key + value --- 
end($a); 
$key = key($a);
$value = current($a);

echo "Last item: ".$key." => ".$value."\n";

?>

如果要检查它在迭代中,end()函数仍可以是有用的:

foreach ($a as $key => $value) {
    if ($value == end($a)) {
      // this is the last element
    }
}

有不少方法可以做到这一点其他的答案无疑会表演。但我建议学习 SPL 和其的 cachingIterator 。下面是一个例子:

<?php

$array = array('first', 'second', 'third');

$object = new CachingIterator(new ArrayIterator($array));
foreach($object as $value) {
    print $value;

    if (!$object->hasNext()) {
        print "<-- that was the last one";
    }
}

这比简单的foreach更详细的,但不是所有的东西。和所有不同的SPL迭代器打开了一个全新的世界为你,一旦你了解他们:)的以下是一个很好的教程。

您可以使用数组指针遍历函数(具体 next ),以确定是否存在当前的一个接一个元素:

$value = reset($kvarr);
do
{
  $key = key($kvarr);
  // Do stuff

  if (($value = next($kvarr)) === FALSE)
  {
    // There is no next element, so this is the last one.
  }
}
while ($value !== FALSE)

请注意,如果您的数组包含其值是FALSE元素这种方法是行不通的,而你需要做你平常的循环体(因为数组指针是通过调用next高级)后处理的最后一个元素要不然memoize的值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top