Search code examples
phparraysloopssumgrouping

Group and sum data that is generate by nested loops


I'd generated an array in PHP through below code. An investor array is taken, multiple investors multiple emi tenure data are pushed. Now I want to build an array emi tenure wise (like result sample).

$investors = array();
for($i = 0; $i < 2 ; $i++){

    //emi-data push start
    $emiTenures = array();
    for($k = 0; $k < 3 ; $k++){
    
        $data =[
            'b_amount' => 1*$k+$i,
            'recv_total' => 1+$k+$i
        ]; 
        array_push($emiTenures,$data);   
    }
    //emi-data push end
    
    array_push($investors,$emiTenures);    
}
print_r($investors);

output of above array:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [b_amount] => 0
                    [recv_total] => 1
                )

            [1] => Array
                (
                    [b_amount] => 1
                    [recv_total] => 2
                )

            [2] => Array
                (
                    [b_amount] => 2
                    [recv_total] => 3
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [b_amount] => 1
                    [recv_total] => 2
                )

            [1] => Array
                (
                    [b_amount] => 2
                    [recv_total] => 3
                )

            [2] => Array
                (
                    [b_amount] => 3
                    [recv_total] => 4
                )

        )

)

result sample : I want to get result array like below : (emiTenures wise)

Array
(
    [0] => Array
        (
            [b_amount] => 1 // $investors[0][0]['b_amount'] + $investors[1][0]['b_amount']
            [recv_total] => 3 // $investors[0][0]['recv_total'] + $investors[1][0]['recv_total']
        )

    [1] => Array
        (
            [b_amount] => 3 // $investors[0][1]['b_amount'] + $investors[1][1]['b_amount']
            [recv_total] => 5 // $investors[0][1]['recv_total'] + $investors[1][1]['recv_total']
        )

    [2] => Array
        (
            [b_amount] => 5
            [recv_total] => 7
        )

)

Solution

  • Group by the $k values on the first level and sum the values that belong in each group.

    Code: (Demo)

    $investors = [];
    for ($i = 0; $i < 2; ++$i) {
        for ($k = 0; $k < 3; ++$k) {
            $investors[$k]['b_amount'] = ($investors[$k]['b_amount'] ?? 0) + 1 * $k + $i;
            $investors[$k]['recv_total'] = ($investors[$k]['recv_total'] ?? 0) + 1 + $k + $i;
        }
    }
    var_export($investors);