0

I have an array containing associative subarrays with keys and value pairs.

The array is in following format:

$info = [
    ['name1' => 'type1', 'count' => '27'],
    ['name1' => 'Type2', 'count' => '11'],
    ['name1' => 'Type1', 'count' => '5'],
    ['name1' => 'Type1', 'count' => '12'],
    ['name1' => 'type2', 'count' => '10']
];

How can I sum the values in the "count" key for each value of the "name1" key, so I would get a result with counts like this?

 ['type1' => 44, 'type2' => 22]
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
peter joseph
  • 15
  • 1
  • 5

3 Answers3

0

The most obvious solution would be to iterate the array:

$counts = array();

foreach($info as $elem){
    $counts[$elem['name1']] += $elem['count'];
}

var_dump($counts);

Output:

Warning: Undefined array key "type1"

Warning: Undefined array key "Type2"

Warning: Undefined array key "Type1"

Warning: Undefined array key "type2"
array(4) {
  ["type1"]=>
  int(27)
  ["Type2"]=>
  int(11)
  ["Type1"]=>
  int(17)
  ["type2"]=>
  int(10)
}

If you want type1 and Type1 to be the same key (case insensitive), you could do something like:

foreach($info as $elem) {
    $counts[strtolower($elem['name1'])] += $elem['count'];
}

Output:

Warning: Undefined array key "type1"

Warning: Undefined array key "type2"
array(2) {
  ["type1"]=>
  int(44)
  ["type2"]=>
  int(21)
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
lpg
  • 4,897
  • 1
  • 16
  • 16
  • Yes sir.ur solution helped me.can u please help in formatting the new array in html structure,I m posting my foreach loop format.I was trying to fomrat like this type1-44 then next row type2-22(in html format)...Please check once – peter joseph Aug 27 '14 at 08:30
0
$new   = array();

foreach ($info as $v)
{
    // Normalize the key names
    $key = ucfirst($v['name1']);

    if (isset($new[$key]))
    {
        $new[$key] += $v['count'];
    }
    else
    {
        $new[$key] = $v['count'];
    }
}

...so then print_r($new); will give you this:

Array
(
    [Type1] => 44
    [Type2] => 21
)
TunaMaxx
  • 1,782
  • 12
  • 18
0

Here's my take on it.

function getTypeArray($arr, $type) {
    return array_filter($arr, function($item) use($type) {
        return strtolower($item['name1']) == $type;
    });
}

function sumArray($arr) {
    return array_sum(array_map(function($item) {
        return $item['count'];
    }, $arr));
}

$type1_count = sumArray(getTypeArray($info, 'type1'));
$type2_count = sumArray(getTypeArray($info, 'type2'));
print 'Type1: '.$type1_count;
print 'Type2: '.$type2_count;
Oskar Hane
  • 1,824
  • 13
  • 8