ds342222 2014-06-09 04:09
浏览 42
已采纳

分块阵列更有效率?

Just trying to find out if there is a more efficient way of chunking an array; I have an array that could be rather large, and I need to chunk it into multidimensional arrays of 3, but only have 4.

This is what I have so far, and it works; but the question is to see if there is a better/faster alternative.

$rows = array_chunk($array, 3);

$top = array();
for ($i = 0; $i < 3; $i++) {
    $top[] = $rows[$i];
}

Notes

The $rows array looks something like this:

array(
    [0] => name,
    [1] => name,
    [2] => name,
    .....etc
)

And I'd just like to chunk it to look like this:

array(
    [0] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [1] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [2] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [3] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    )
)

And for those who don't bother reading, I do already have something that works (as stated above), I'm just trying to optimize it as it's quite possibly the ugliest way to do it.

  • 写回答

1条回答 默认 最新

  • dsafgdafgdf45345 2014-06-09 04:19
    关注
    //make sure to copy the sliced values into a different array
    $slice = array_slice($array,0,12);
    $rows = array_chunk($slice,3);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver