php mathematical addition of numerical values in 2 associative arrays
-
24-10-2019 - |
Pergunta
Probably a simple one for you :
I have 2 arrays
$array1 = array(
'foo' => 5,
'bar' => 10,
'baz' => 6
);
$array2 = array(
'x' => 100,
'y' => 200,
'baz' => 30
);
I wish to get a third array by combining both the above, which should be :
$result_array = array(
'foo' => 5,
'bar' => 10,
'baz' => 36,
'x' => 100,
'y' => 200,
);
Is there any built in 'array - way' to do this, or will I have to write my own function ? Thanks
Solução
$resultArray = $array1;
foreach($array2 as $key => $value) {
if (isset($resultArray[$key])) {
$resultArray[$key] += $value;
} else {
$resultArray[$key] = $value;
}
}
Outras dicas
There's no built-in function for this, you'll have to write your own.
you need
$newArray = $array1;
foreach($array2 as $key => $value) {
if(array_key_exists($key, $newArray)){
$newArray[$key] += $value;
}else{
$newArray[$key] = $value;
}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow