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]
The most obvious solution would be to iterate the array:
$counts = array();
foreach($info as $elem){
$counts[$elem['name1']] += $elem['count'];
}
var_dump($counts);
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'];
}
$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
)
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.