我有这个代码
$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
,你不需要将其简化为数组。您可以简单地使用迭代器本身的count
和append
方法:
$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
的一半以上。