phparraysmultidimensional-arraysumgrouping

Create an associative element by grouping 2d array data by one column and summing another column per group


I have an existing array that looks a bit like this

Array
(
[0] => Array
    (
        [author] => Gavin
        [weighting] => 2743
    )

[1] => Array
    (
        [author] => Bob
        [weighting] => 2546
    )

[2] => Array
    (
        [author] => Gavin
        [weighting] => 2227
    )
)

Now what I want to do is loop through that and end up with a new array that has 2 keys (Gavin and Bob) and Bob's value is 2546 while Gavin's is 4970.

Right now I have this which nearly works but the last author gets a duplicate value and I can't sort it?

if (array_key_exists($authorName, $Authors)) {
    foreach ($Authors as $key_name => &$key_value) {
        if ($key_name == $authorName)
        {
                $key_value = $key_value + $weight;
        }
    }
}
else {
    $Authors[$authorName] = $weight;
}

What am I doing wrong here?


Solution

  • This should do the trick

    $newarray = array();
    foreach($yourarray as $a) {
        //create array if not created
        if(!isset($newarray[$a['author']])) {
            $newarray[$a['author']] = 0;
        }
        //put value in array
        $newarray[$a['author']] += $a['weighting'];
    }