如何通过汇总每个项目来对数组中的项目进行分组

时间:2016-08-02 02:47:22

标签: php

DataRow

当summmary每个项目> = 35将自动创建子数组

if ($_REQUEST['ss_name'] == 'John'){
    redirect('http://localhost/homepage_loggedin_book_john.php');
}elseif($_REQUEST['ss_name'] == 'Smith'){
    redirect('http://localhost/homepage_loggedin_book_smith.php');
}

if ($_REQUEST['ss_name'] == 'John') {
    header("Location: http://localhost/homepage_loggedin_book_john.php");
} else if ($_REQUEST['ss_name'] == 'Smith') {
    header("Location: http://localhost/homepage_loggedin_book_smith.php");
} 

2 个答案:

答案 0 :(得分:2)

$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
//         )

// )

答案 1 :(得分:0)

我知道,也许你想要的答案如下,

$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;
for each($quantity as $value) {
    $sum_quantity += $value;
    if($sum_quantity >= 35) {
        $i++;
        $output_array[$i][] = $value;
        $sum_quantity = $value;
    }else{
        $output_array[$i][] = $value;
    }

}
print_r($output_array);

我试过测试,没关系。