使用 PHP - SPL 解决方案反向迭代数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5315539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:58:50  来源:igfitidea点击:

Iterate in reverse through an array with PHP - SPL solution?

phpreverseloopsspl

提问by Sebastian Hoitz

Is there an SPL Reverse array iterator in PHP? And if not, what would be the best way to achieve it?

PHP 中是否有 SPL 反向数组迭代器?如果没有,实现它的最佳方法是什么?

I could simply do

我可以简单地做

$array = array_reverse($array);
foreach($array as $currentElement) {}

or

或者

for($i = count($array) - 1; $i >= 0; $i--)
{

}

But is there a more elegant way?

但是有没有更优雅的方式呢?

采纳答案by Gordon

There is no ReverseArrayIteratorto do that. You can do

没有ReverseArrayIterator这样做。你可以做

$reverted = new ArrayIterator(array_reverse($data));

or make that into your own custom iterator, e.g.

或者把它变成你自己的自定义迭代器,例如

class ReverseArrayIterator extends ArrayIterator 
{
    public function __construct(array $array)
    {
        parent::__construct(array_reverse($array));
    }
}

回答by linepogl

Here is a solution that does not copy and does not modify the array:

这是一个不复制也不修改数组的解决方案:

for (end($array); key($array)!==null; prev($array)){
  $currentElement = current($array);
  // ...
}

If you also want a reference to the current key:

如果您还想引用当前密钥:

for (end($array); ($currentKey=key($array))!==null; prev($array)){
  $currentElement = current($array);
  // ...
}

This works always as php array keys can never be null and is faster than any other answer given here.

这始终有效,因为 php 数组键永远不能为空,并且比此处给出的任何其他答案都快。

回答by AbiusX

$item=end($array);
do {
...
} while ($item=prev($array));

回答by rr.

Depending on what you are trying to do, you might want to look into the spl data structure classes, such as SplStack. SplStack implements Iterator, ArrayAccess and Countable, so it can mostly be used like an array, but by default, its iterator proceeds in FILO order. Ex:

根据您尝试执行的操作,您可能需要查看 spl 数据结构类,例如 SplStack。SplStack 实现了 Iterator、ArrayAccess 和 Countable,因此它主要可以像数组一样使用,但默认情况下,它的迭代器以 FILO 顺序进行。前任:

$stack = new SplStack();
$stack[] = 'one';
$stack[] = 'two';
$stack[] = 'three';

foreach ($stack as $item)
{
    print "$item\n";
}

This will print

这将打印

three
two
one

回答by mpen

Based on linepogl's answer, I came up with this function:

根据linepogl 的回答,我想出了这个功能:

/**
 * Iterate an array or other foreach-able without making a copy of it.
 *
 * @param array|\Traversable $iterable
 * @return Generator
 */
function iter_reverse($iterable) {
    for (end($iterable); ($key=key($iterable))!==null; prev($iterable)){
        yield $key => current($iterable);
    }
}

Usage:

用法:

foreach(iter_reverse($my_array) as $key => $value) {
    // ... do things ...
}

This works on arrays and other iterables without first making a copy of it.

这适用于数组和其他可迭代对象,而无需先复制它。

回答by Rob Allen

Note that if you want to preserve the keys of the array, you must pass trueas the second parameter to array_reverse:

请注意,如果要保留数组的键,则必须将其true作为第二个参数传递给array_reverse

$array = array_reverse($array, true);
foreach ($array as $currentElement) {
    // do something here
}

回答by Gaurav

$array = array_reverse($array);
foreach($array as $key => $currentElement) {}

This is better way to use. It will take care of keys also, if they are not sequential or integer.

这是更好的使用方式。如果键不是连续的或整数,它也会处理键。

回答by C.M.

Based on linepogl'sanswer... You can make it even more efficient by avoiding current()call

基于linepogl 的回答......您可以通过避免current()通话来提高效率

for ($value = end($array); ($key = key($array)) !== null; $value = prev($array)) {
     // ... do something with $key => $value
}

回答by Tadej Kobe

$array=array(
    0 => 0,
    '1' => 1,
    2 => null,
    3 => false
);

$value=end( $array );                      // ← value for first iteration
while(($key=key( $array )) !== null) {
  echo "key=$key, value=$value\n";

  $value=prev( $array );                   // ← value for next iteration
}

回答by bitluni

This could be a more performant way since it doesnt construct a new array. It also handles empty arrays well.

这可能是一种更高效的方式,因为它不构造新数组。它还可以很好地处理空数组。

$item = end($items);
while($item)
{
    ...do stuff...
    $item = prev($items);
}