doumiebiao6827 2017-01-01 11:41
浏览 52
已采纳

PHP - 根据内容将数组拆分为块

I have an php array that that i would like split to up into smaller chunks using a loop.

Once all elements with the same values have been pushed into the chunk, i want to use that chunk for something, then continue the loop and setup the next chunk, until all content of the original $array has been used.

public function adjust($array){ 
  // $array = [1, 1, 2, 2, 8, 8, 8, 9, 20]

  $chunk = array()

  for ($i = 0; $i < sizeof($array); $i++){
   // code here
   // result should be $chunk = [1, 1] 
   // use $chunk for something, reset its contents, 
   // continue loop until chunk is [2, 2],
   // rinse and repeat
 }    
}

I dont necesarrily need a loop, i just require to be able to slice $array into 5 $chunks (for this specific example), to be able to process the data.

Is there an easier way to solve this without a bunch of if/else clauses ?

  • 写回答

2条回答 默认 最新

  • duanqiao2006 2017-01-01 11:56
    关注

    Initialize $chunk to an array containing the first element. Then loop through the rest of the array, comparing the current element to what's in $chunk. If it's different, process $chunk and reset it.

    $chunk = array[$array[0]];
    for ($i = 1; $i < count($array); $i++) {
        if ($array[$i] != $chunk[0]) {
            // use $chunk for something
            $chunk = array($array[$i]);
        } else {
            $chunk[] = $array[$i];
        }
    }
    // process the last $chunk here when loop is done
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看