The sum of PHP by another field from a unique identifier in an array

I have a multidimensional array like this:

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 summarize the field totalto end in such an array:

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 tried array_unique, but it only removes duplicates ...

+4
source share
5 answers

Try this code: sandbox code
The main idea of ​​the algorithm is to cache key pairs in an array of results and further check their existence.

$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);
+4
source

Try it,

$arrays = array_values(array_combine(array_map(function ($i) { return $i['id']; }, $array), $array));    
print_r($arrays);

Demo

0
source

, .

$input = 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)
);
// This is where we will save our result
$output = array();

foreach ($input as $item) {
    // Used to determine if the current $item 
    // already exists in the $output array
    $foundItem = false;
    // Now we check the $item against every output entry
    foreach ($output as &$entry) {
        if ($entry["id"] == $item["id"]) {
            // Since we found a match, let add the 
            //current item total to the output total.
            $entry["total"] += $item["total"];
            // Marking this as true will later prevent us 
            // from inserting the item to the output array twice
            $foundItem = true;
        }
    }
    // If the item was not found in the output array
    // the $foundItem variable remains false
    // Using ! to negate the boolean, we insert the item to the output array
    if (!$foundItem) {
        $output[] = $item;
    }
}

, . , , . .

0

, ,

$array = array(
    array('id' => 1, 'name' => 'Agent 1', 'total' => 3),
    array('id' => 2, 'name' => 'Agent 2', 'total' => 3),
    array('id' => 3, 'name' => 'Agent 3', 'total' => 3),
    array('id' => 1, 'name' => 'Agent 1', 'total' => 6)
);
$array_ids = array();

foreach ($array as $key => $value) {
    if (isset($array_ids[$value['id']])) {
        $array[$array_ids[$value['id']]]['total'] += $value['total'];
        unset($array[$key]);
    }
    else
    {
        $array_ids[$value['id']] = $key;
    }
}

id $array_ids, ,

0

array_reduce - . . , .

<?php   
$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],
    ];

$result = array_reduce($array, function($temp, $item){
    isset($temp[$item['id']])
       ? $temp[$item['id']]['total'] += $item['total']
       : $temp[$item['id']] = $item;
    return $temp;
}, []);

print_r($result);
?>

OUTPUT

(

[1] = > ([id] = > 1 [name] = > 1 [total] = > 9)

[2] = > ([id] = > 2 [name] = > 2 [total] = > 3)

[3] = > ([id] = > 3 [name] = > 3 [total] = > 3)

)

0

Source: https://habr.com/ru/post/1662513/


All Articles