fork download
  1. <?php
  2.  
  3. // your code goes here
  4.  
  5. $initData = [
  6. ['id'=>1,'amount'=>10],
  7. ['id'=>2,'amount'=>8],
  8. ['id'=>3,'amount'=>7],
  9. ['id'=>4,'amount'=>9],
  10. ['id'=>5,'amount'=>8],
  11. ['id'=>6,'amount'=>11],
  12. ['id'=>7,'amount'=>8],
  13. ['id'=>8,'amount'=>9],
  14. ];
  15.  
  16. $res1 =[]; // to insert
  17. $res2 = []; //to insert total
  18.  
  19. $total = 0;
  20. $i=1;
  21. foreach($initData as $row){
  22. if($total+$row['amount']>20) {
  23. $res2[] = ['i'=>$i,'total'=>$total];
  24. foreach($tempArr as $data){
  25. $res1[] = $data;
  26. }
  27. $i++;
  28. $tempArr = [];
  29. $total = 0;
  30. }
  31. $total += $row['amount'];
  32. $row['i'] = $i;
  33. $tempArr[] = $row;
  34. }
  35. if($total>0) {
  36. $res2[] = ['i'=>$i,'total'=>$total];
  37. foreach($tempArr as $data){
  38. $res1[] = $data;
  39. }
  40.  
  41. }
  42.  
  43. print_r($res1);
  44. print_r($res2);
Success #stdin #stdout 0.02s 23828KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [id] => 1
            [amount] => 10
            [i] => 1
        )

    [1] => Array
        (
            [id] => 2
            [amount] => 8
            [i] => 1
        )

    [2] => Array
        (
            [id] => 3
            [amount] => 7
            [i] => 2
        )

    [3] => Array
        (
            [id] => 4
            [amount] => 9
            [i] => 2
        )

    [4] => Array
        (
            [id] => 5
            [amount] => 8
            [i] => 3
        )

    [5] => Array
        (
            [id] => 6
            [amount] => 11
            [i] => 3
        )

    [6] => Array
        (
            [id] => 7
            [amount] => 8
            [i] => 4
        )

    [7] => Array
        (
            [id] => 8
            [amount] => 9
            [i] => 4
        )

)
Array
(
    [0] => Array
        (
            [i] => 1
            [total] => 18
        )

    [1] => Array
        (
            [i] => 2
            [total] => 16
        )

    [2] => Array
        (
            [i] => 3
            [total] => 19
        )

    [3] => Array
        (
            [i] => 4
            [total] => 17
        )

)