Ryan
Ryan

Reputation: 15270

How can I group by a count of a subvalue of an array?

I've been trying every combination of array_count_values and array_map I can think of. I'm hoping you can show me the way.

Here's a sample array:

$arr = array(
            array('name' => 'foo','score' => 1),
            array('name' => 'foo','score' => 2),
            array('name' => 'bar','score' => 1)
        );

I'd like to combine the scores of all sub values with the same name. Something like GROUP BY name in MySQL.

Array
(
    [0] => Array
        (
            [name] => foo
            [score] => 3
        )

    [1] => Array
        (
            [name] => bar
            [score] => 1
        )
)

I know there are other questions that sort multidimensional arrays, but I'm not able to find one that sums one of the sub values along the way.

Upvotes: 0

Views: 141

Answers (1)

Baba
Baba

Reputation: 95121

You can use array_reduce

$arr = array(
        array('name' => 'foo','score' => 1),
        array('name' => 'foo','score' => 2),
        array('name' => 'bar','score' => 1));

$array = array_reduce($arr, function ($a, $b) {
    isset($a[$b['name']]['score']) ? $a[$b['name']]['score'] += $b['score'] : $a[$b['name']] = $b;
    return $a;
});

var_dump($array);

Output

array
  'foo' => 
    array
      'name' => string 'foo' (length=3)
      'score' => int 3
  'bar' => 
    array
      'name' => string 'bar' (length=3)
      'score' => int 1

Upvotes: 1

Related Questions