php - Create an array from two associative array -
i've 2 arrays bellow:
array (size=2) 827 => int 3 868 => int 3 array (size=4) 827 => int 2 868 => int 2 829 => int 1 541 => int 1
i want combine 2 arrays , add values when keys matches. resulting array needs be:
array (size=4) 827 => int 5 868 => int 5 829 => int 1 541 => int 1
tried different array manipulation function none of them worked. appreciated.
you can following: using +
on arrays, creating new array, have key/values of both, duplicates not overriden second one. after can loop again on second array , and add values (but if value not present in $a1). if not present in $a1, value in merged array $a2.
$a1 = array(827 => 3, 868 => 3); $a2 = array(827 => 2, 868 => 2, 829 => 1, 541 => 1); $merged = $a1+$a2; foreach($a2 $key => $value){ if(!empty($a1[$key])){ $merged[$key] = $merged[$key] + $value; } }
Comments
Post a Comment