小编典典

合并2个数组并求和(数字键)

mysql

我有2个数组

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)



Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

我是否可以将这些单独的数组合并为一个并将这些值相加,以便结果为:

Array
(
    [010156] => Array
    (
        [supp_number] =&gt;  <<<TOTAL >>>
        [totalamount] =&gt;     <<<TOTAL >>>
        [debtorcred] =&gt; <<<TOTAL >>>
        [amount1] =&gt;      <<<TOTAL >>>
        [amount2] =&gt;  <<<TOTAL >>>

        [amount3] =&gt;  <<<TOTAL >>>
        [amount4] =&gt;  <<<TOTAL >>>
        [amount5] =&gt;  <<<TOTAL >>>
        [amount6] =&gt;  <<<TOTAL >>>
    )
)

这是我目前拥有的功能,但我似乎无法使其工作:

function array_merge_numeric_values()
{
  $arrays = func_get_args();
  $merged = array();
  foreach ($arrays as $array)
  {
    foreach ($array as $key => $value)
    {
      if ( ! isset($merged[$key]))
      {
        $merged[$key] = $value;
      }
      else
      {
        $merged[$key] += $value;
      }
    }
  }

阅读 365

收藏
2020-05-17

共1个答案

小编典典

可以用两行代码完成此实际计算,而无需循环:

http://codepad.viper-7.com/ieSkHQ

$arr1 = array('amount1' => 1, 'amount2' => 6);
$arr2 = array('amount1' => 2, 'amount2' => 7);
$add = function($a, $b) { return $a + $b; };
$summedArray = array_map($add, $arr1, $arr2);
print_r($summedArray);

您只需要进行适当的调整即可解决您的嵌套结构。

2020-05-17