1

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

使用 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

);
4

3 回答 3

1

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

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

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

于 2013-07-08T15:54:16.473 回答
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;
}
于 2013-07-08T17:48:32.197 回答
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);
于 2013-07-08T15:58:52.070 回答