PHPにSPL逆配列イテレータはありますか? そうでない場合、それを達成するための最良の方法は何ですか?
私は単に行うことができます
$array = array_reverse($array);
foreach($array as $currentElement) {}
また
for($i = count($array) - 1; $i >= 0; $i--)
{
}
しかし、もっとエレガントな方法はありますか?
$item=end($array);
do {
...
} while ($item=prev($array));
それをする必要はありませReverseArrayIterator
ん。できるよ
$reverted = new ArrayIterator(array_reverse($data));
または、それを独自のカスタムイテレータにします。
class ReverseArrayIterator extends ArrayIterator
{
public function __construct(array $array)
{
parent::__construct(array_reverse($array));
}
}
を使用しないarray_reverse
が、標準の配列関数を介して配列を反復する少し長い実装は、次のようになります。
class ReverseArrayIterator implements Iterator
{
private $array;
public function __construct(array $array)
{
$this->array = $array;
}
public function current()
{
return current($this->array);
}
public function next()
{
return prev($this->array);
}
public function key()
{
return key($this->array);
}
public function valid()
{
return key($this->array) !== null;
}
public function rewind()
{
end($this->array);
}
}
linepogl's answerに基づいて、私はこの関数を思いつきました:
/**
* 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);
}
}
使用法:
foreach(iter_reverse($my_array) as $key => $value) {
// ... do things ...
}
これは、最初にコピーを作成しなくても、配列やその他のイテラブルで機能します。
何をしようとしているのかによっては、SplStack などの spl データ構造クラスを調べることができます。SplStack は Iterator、ArrayAccess、および Countable を実装しているため、ほとんどが配列のように使用できますが、デフォルトでは、その反復子は FILO 順で処理されます。元:
$stack = new SplStack();
$stack[] = 'one';
$stack[] = 'two';
$stack[] = 'three';
foreach ($stack as $item)
{
print "$item\n";
}
これは印刷されます
three
two
one
true
配列のキーを保持する場合は、2番目のパラメーターとしてarray_reverse
:に渡す必要があることに注意してください。
$array = array_reverse($array, true);
foreach ($array as $currentElement) {
// do something here
}
$array = array_reverse($array);
foreach($array as $key => $currentElement) {}
これはより良い使用方法です。キーがシーケンシャルまたは整数でない場合、キーも処理します。
$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
}
これは、新しい配列を構築しないため、よりパフォーマンスの高い方法になる可能性があります。また、空の配列も適切に処理します。
$item = end($items);
while($item)
{
...do stuff...
$item = prev($items);
}
$array1=配列(10,20,30,40,50);
for($i = count($array1) - 1; $i >= 0; $i--)
{
$array2[] = $array1[$i];
}
echo "<pre>";
print_r($array2);
echo "</pre>";