简体   繁体   English

在关联数组中查找最后一对

[英]Finding last pair in associative array

I'm looping through an associative array with a foreach. 我正在使用foreach循环关联数组。 I'd like to be able to check if the key value pair being handled is the last so I can give it special treatment. 我希望能够检查正在处理的键值对是否是最后一个,所以我可以给它特殊的处理。 Any ideas how I can do this the best way? 我有什么想法可以做到最好吗?

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
}

Simple as this, free from counters and other 'hacks'. 这很简单,没有柜台和其他'黑客'。

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

   // your stuff

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

Please note that you have to use === , because the function next() may return a non-boolean value which evaluates to false , such as 0 or "" (empty string). 请注意,您必须使用=== ,因为函数next()可能返回一个非布尔值,其值为false ,例如0或“”(空字符串)。

we don't need to iterate through the array with foreach, we can use the end(), key() and current() php functions to get to the last element and get it's key + value. 我们不需要使用foreach迭代数组,我们可以使用end(),key()和current()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";

?>

If you want to check it in the iteration, the end() function still can be useful: 如果要在迭代中检查它,end()函数仍然有用:

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

There are quite a few ways to do that as other answers will no doubt show. 有很多方法可以做到这一点,因为其他答案无疑会显示出来。 But I would suggest to learn SPL and its CachingIterator . 但我建议学习SPL及其CachingIterator Here is an example: 这是一个例子:

<?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";
    }
}

It is more verbose than simple foreach, but not all that much. 它比简单的foreach更冗长,但并不是那么多。 And all the different SPL iterators open up a whole new world for you, once you learn them :) Here is a nice tutorial. 一旦你学会了它们,所有不同的SPL迭代器都会为你打开一个全新的世界:) 这是一个很好的教程。

Assuming you're not altering the array while iterating through it, you could maintain a counter that decrements in the loop and once it reaches 0, you're handling the last: 假设你在迭代它时没有改变数组,你可以维护一个在循环中递减的计数器,一旦它达到0,你就处理最后一个:

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

You could use the array pointer traversal functions (specifically next ) to determine if there is another element after the current one: 您可以使用数组指针遍历函数(特别是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)

Note that this method won't work if your array contains elements whose value is FALSE , and you'll need to handle the last element after doing your usual loop body (because the array pointer is advanced by calling next ) or else memoize the value. 请注意,如果您的数组包含值为FALSE元素,则此方法将不起作用,并且您需要在执行常用循环体之后处理最后一个元素(因为通过调用next来提升数组指针)或者记住值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM