Combine arrays, count values and total in PHP
After many attempts to crack this I am stuck so I turn to SO for help.
I have two arrays, as below. The keys from both arrays are relational to each other. I need to combine both arrays together as a key=>value pair.
for example:
[Internet Explorer] => 3
[Internet Explorer] => 2
However, following this I need to total the values of the duplicate keys. Resulting in a unique total key=>value pair for each browser.
for example:
[Internet Explorer] => 5
[Google Chrome] => 3
Thank you for looking, I have tried many array functions and I always come to the same result of getting unique keys without totalised values.
Array
(
[0] => Unknown
[1] => Unknown
[2] => Unknown
[3] => Internet Explorer
[4] => Internet Explorer
[5] => Mozilla Firefox
[6] => Internet Explorer
[7] => Unknown
[8] => Unknown
[9] => Google Chrome
[10] => Google Chrome
[11] => Mozilla Firefox
[12] => Mozilla Firefox
[13] => Unknown
)
Array
(
[0] => 1
[1] => 2
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[10] => 1
[11] => 1
[12] => 2
[13] => 1
)
Ed开发者_JAVA百科it: Adding code for clarity.
$agent_list is the result of a query which collects unique instances of USER AGENT and counts them.
The getBrowser function searches each $agents and extracts the browser type.$agents = array();
$agents_count = array();
foreach($agent_list as $value1)
{
$agent = getBrowser($value1['agent']);
array_push($agents,$agent);
array_push($agents_count,(int)$value1['count']);
}
Assuming the keys array is $keys
and the values array is $values
, this should work.
$result = array_fill_keys(array_unique($keys), 0);
foreach($keys as $i=>$k){
$result[$k] += $values[$i];
}
Demo: http://ideone.com/9EIOU
Why not iterate over one array and add values if they exists or append if they don't exist:
foreach($array1 as $key => $value){
$array2[$key] += $value;
}
This will ad the value or add the key with the value if it doesn't exist in $array2
.
Hope, I understand your question
Let $a
,$b
are input arrays, result will be in $a
foreach($b as $k=>$v){
if(isset($a[$k]))
$a[$k]+=$v;
else
$a[$k]=$v;
}
精彩评论