# php 两个数组，若键相同，则值合并

0
[待解决问题]

\$arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
\$arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');

\$arr3 = array('8' => '0.01', '9' => '4.08', '10' => '0.11', '11' => '4.09', '12' => '0.01');

0

``````<!DOCTYPE html>
<html>
<body>

<?php
\$arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
\$arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');
\$arr3 = \$arr1;//把数组1赋值给新的数组3

foreach(\$arr2 as \$x=>\$x_value)//遍历数组2
{
if (array_key_exists(\$x, \$arr3)) {//如果存在key，则值相加
\$arr3[\$x] += \$arr2[\$x];
}
else {//不存在key，则新增
\$arr3[\$x] = \$x_value;
}
}
ksort(\$arr3);//根据key进行升序排列

foreach(\$arr3 as \$x=>\$x_value)
{
echo "Key=" . \$x . ", Value=" . \$x_value;
echo "<br>";
}
?>

</body>
</html>``````

0

\$arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01');
\$arr2 = array('8' => '0.01', '10' => '0.01', '11' => '0.01');
\$arr = [];

``````    foreach (\$arr1 as \$key => \$value) {
if(isset(\$arr[\$key])){
\$arr[\$key] += \$value;
}else{
\$arr[\$key] = \$value;
}
}

foreach (\$arr2 as \$key => \$value) {
if(isset(\$arr[\$key])){
\$arr[\$key] += \$value;
}else{
\$arr[\$key] = \$value;
}
}

ksort(\$arr);``````

您需要登录以后才能回答，未注册用户请先注册