我有这个密码
$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对象有两个不同的项集。
发布于 2012-04-13 05:22:16
看来您可以使用getArrayCopy方法的ArrayIterator。这将返回一个数组,然后可以对其进行操作。
至于将一半结果分配给新ArrayIterator,另一半分配给另一个ArrayIterator,则不需要将其还原为数组。您可以简单地使用Iterator本身的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
)根据需要修改三元条件。
发布于 2017-12-12 12:07:41
$first_half = new LimitIterator($items, 0, ceil(count($items) / 2));
$second_half = new LimitIterator($items, iterator_count($first_half));这将使您获得2个迭代器,它将允许您只迭代原始$items的一半以上。
https://stackoverflow.com/questions/10135591
复制相似问题