php结合数组键值?

时间:2013-07-08 15:46:38

标签: php arrays key

我希望将两个数组合并为一个数组,但我希望保持键值相同并将它们的值累加到一个数组中。

使用PHP我正在寻找这样的东西:

//inputs
array(
   cat => 4,
   dog => 3,
   bug => 6

);

array(
   cat => 2,
   dog => 5,
   bug => 9,
   ant => 3

);


//output
array(
   cat => 6,
   dog => 8,
   bug => 15,
   ant => 3

);

3 个答案:

答案 0 :(得分:1)

您可以通过添加每个索引来添加数组:(这假设您的第一个数组是array1,依此类推)

<?php
for ($i = 1; $i <= 4; $i ++) {
    $array3[i] = $array1[i] + $array2[i];
}
?>

假设每个数组中都有4个变量。

答案 1 :(得分:0)

function func(&$value, $key) {
    $value = (isset($value[1]) ? $value[0] + $value[1] : $value[0]);
}

$new_array = array_merge_recursive($array1, $array2);
array_walk($new_array, 'func');
print_r($new_array);

答案 2 :(得分:0)

$final_array = array ();

// u can iterate and get the name of the key while doing so, like so
// add the first array
foreach ($array1 as $prop=>$val)
{
    $final_array[$prop]+=$val;
}


//add the second array
foreach ($array2 as $prop=>$val)
{
    $final_array[$prop]+=$val;
}

//result is in final_array

//or more efficiently, just add the second to the first
foreach ($array2 as $prop=>$val)
{
    $array1[$prop]+=$val;
}