haitruonginfotech haitruonginfotech - 4 months ago 7
PHP Question

How to group items in array by summary each item

<?php
$quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16);
// Create a new array
$output_array = array();
$sum_quantity = 0;
$i = 0;
foreach ($quantity as $value) {
if($sum_quantity >= 35) {
$output_array[$i][] = $value;
}
$sum_quantity = $sum_quantity + $value;
}
print_r($output_array);


When summmary each item >= 35 will auto create child array

array(
[0] => array(1, 2, 3, 4, 5, 6, 7),
[1] => array(8, 9, 10),
[2] => array(11, 12, 1),
[3] => array(14, 2, 16)
)

Answer
$quantity = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 14, 2, 16);

// Create a new array
$output_array = array();
$current_array = array();
$current_sum = 0;

foreach ($quantity as $value) {
    $current_sum += $value;
    if ($current_sum >= 35) {
        $output_array[] = $current_array;
        $current_array = array();
        $current_sum = $value;
    }
    $current_array[] = $value;
}
$output_array[] = $current_array;

print_r($output_array);

// Output:
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 4
//             [4] => 5
//             [5] => 6
//             [6] => 7
//         )

//     [1] => Array
//         (
//             [0] => 8
//             [1] => 9
//             [2] => 10
//         )

//     [2] => Array
//         (
//             [0] => 11
//             [1] => 12
//             [2] => 1
//         )

//     [3] => Array
//         (
//             [0] => 14
//             [1] => 2
//             [2] => 16
//         )

// )
Comments