如何将数组迭代器一分为二


How to slice ArrayIterator into two?

我有这个代码

$second_half = $items; //ArrayIterator Object;
$first_half = array_slice($second_half ,0,ceil(count($second_half)/2));

这给出了警告警告:array_slice() 期望参数 1 是数组,对象给定有没有办法将ArrayIterator对象切成两半?

基本上,我想要存储在$first_half中未知数量的项目的一半,其余的项目$second_half;结果将是两个ArrayIterator对象,具有两组不同的项目。

看起来你可以使用 ArrayIterator 的 getArrayCopy 方法。这将返回一个数组,然后您可以对其进行操作。

至于将结果的一半分配给新ArrayIterator,另一半分配给另一个ArrayIterator,你不需要将其简化为数组。您可以简单地使用迭代器本身的countappend方法:

$group = new ArrayIterator;
$partA = new ArrayIterator;
$partB = new ArrayIterator;
$group->append( "Foo" );
$group->append( "Bar" );
$group->append( "Fiz" );
$group->append( "Buz" );
$group->append( "Tim" );
foreach ( $group as $key => $value ) {
  ( $key < ( $group->count() / 2 ) ) 
    ? $partA->append( $value ) 
    : $partB->append( $value );
}

这导致正在构建两个新的ArrayIterator

ArrayIterator Object ( $partA )
(
    [0] => Foo
    [1] => Bar
    [2] => Fiz
)
ArrayIterator Object ( $partB )
(
    [0] => Buz
    [1] => Tim
)

根据需要修改三元条件。

$first_half = new LimitIterator($items, 0, ceil(count($items) / 2));
$second_half = new LimitIterator($items, iterator_count($first_half));

这将为您提供 2 个迭代器,这将允许您只迭代原始$items的一半以上。