WdarinS WdarinS - 4 days ago 5
PHP Question

PHP sum by other field from unique id in array

I have an multidimensional array like this one:

Array
(
[0] => array('id'=>1,'name'=>'Agent 1','total'=>3)
[1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
[2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
[3] => array('id'=>1,'name'=>'Agent 1','total'=>6)
)


And I want to remove duplicate agents from this array and sum the
total
field to end up in a array like this:

Array
(
[0] => array('id'=>1,'name'=>'Agent 1','total'=>9)
[1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
[2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
)


I have tried
array_unique
but it only remove duplicates...

Answer

Try this code: sandbox code
Main idea of algorithm - caching key pairs in result array and further checking existence of them.

$array = [
    0 => ['id' => 1, 'name' => 'Agent 1', 'total' => 3],
    1 => ['id' => 2, 'name' => 'Agent 2', 'total' => 3],
    2 => ['id' => 3, 'name' => 'Agent 3', 'total' => 3],
    3 => ['id' => 1, 'name' => 'Agent 1', 'total' => 6],
];

$sumArray = [];

foreach ($array as $agentInfo) {

    // create new item in result array if pair 'id'+'name' not exists
    if (!isset($sumArray[$agentInfo['id'].$agentInfo['name']])) {
        $sumArray[$agentInfo['id'].$agentInfo['name']] = $agentInfo;
    } else {
        // apply sum to existing element otherwise
        $sumArray[$agentInfo['id'].$agentInfo['name']]['total'] += $agentInfo['total'];
    }
}

// optional action to flush keys of array
$sumArray = array_values($sumArray);

print_r ($sumArray);
Comments