Shakeel Shakeel - 5 months ago 12
PHP Question

Aggregate sum multidimensional arrays grouped by name

I have an array as follows

Array
(
[0] => Array
(
[operation_name] => test 1
[capacity] => 180
)

[1] => Array
(
[operation_name] => Operation 2
[capacity] => 251
)

[2] => Array
(
[operation_name] => Operation 2
[capacity] => 241
)

[3] => Array
(
[operation_name] => Operation 3
[capacity] => 554
)

)


I want to sum the "capacity" key value of same "operation_name" key arrays and made it as a one array.

In the above array I need to sum the following 2 arrays,

[1] => Array
(
[operation_name] => Operation 2
[capacity] => 251
)

[2] => Array
(
[operation_name] => Operation 2
[capacity] => 241
)


And output the resulting array as below.

Array
(
[0] => Array
(
[operation_name] => test 1
[capacity] => 180
)

[1] => Array
(
[operation_name] => Operation 2
[capacity] => 492
)

[2] => Array
(
[operation_name] => Operation 3
[capacity] => 554
)

)


How to do this with php?

Answer

Using simple foreach:

<?php    
$arr = Array
(
    Array
        (
            "operation_name" => "test 1",
            "capacity" => 180
        ),

    Array
        (
            "operation_name" => "Operation 2",
            "capacity" => 251
        ),

    Array
        (
            "operation_name" => "Operation 2",
            "capacity" => 241
        ),

    Array
        (
            "operation_name" => "Operation 3",
            "capacity" => 554
        )

);


$tmpArr = [];

//Finding the sum
foreach ($arr as $value) {
    $key = $value['operation_name'];
    if(array_key_exists($key, $tmpArr)){   //Check if key exists, if so add otherwise add a new entry
        $tmpArr[$key] += $value['capacity'];
    } else {
        $tmpArr[$key] = $value['capacity'];
    }
}

$finalArr = [];

//Creating desired array
foreach ($tmpArr as $key => $value) {
    $Arr['operation_name'] = $key;
    $Arr['capacity'] = $value;
    $finalArr[] = $Arr;
}

print_r($finalArr);

Result:

Array
(
    [0] => Array
        (
            [operation_name] => test 1
            [capacity] => 180
        )

    [1] => Array
        (
            [operation_name] => Operation 2
            [capacity] => 492
        )

    [2] => Array
        (
            [operation_name] => Operation 3
            [capacity] => 554
        )

)

One looper:

$finalArr = [];
foreach ($arr as $value) {
    $key = $value['operation_name'];
    if(array_key_exists($key, $finalArr)){
        $finalArr[$key]['capacity'] += $value['capacity'];
    } else {
        $finalArr[$key] = $value;
    }
}

print_r(array_values($finalArr));