doudao1922 2012-04-13 05:15
浏览 57
已采纳

如何将ArrayIterator切成两部分?

I've got this code

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

This gives the warning Warning: array_slice() expects parameter 1 to be array, object given Is there a way to slice an ArrayIterator object in two?

Basically I want one half of the unknown amount of items stored in $first_half and the remaining items $second_half; the result would be two ArrayIterator objects with two different sets of items.

  • 写回答

2条回答 默认 最新

  • du9757 2012-04-13 05:22
    关注

    It would appear you can use the getArrayCopy method of the ArrayIterator. This will return an array that you can then manipulate.

    As for assigning one half of the results to a new ArrayIterator, and the other half to another ArrayIterator, you wouldn't need to reduce it to an array. You could simply use the count and append methods of the Iterator itself:

    $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 );
    }
    

    This results in two new ArrayIterator's being constructed:

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

    Modify the ternary condition as needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch