合并2个数组并求值(数值键)

时间:2011-08-18 10:06:48

标签: php mysql arrays

我有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;
      }
    }
  }

3 个答案:

答案 0 :(得分:5)

这个实际计算可以用两行代码完成,不需要循环:

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);

您只需进行适当的调整即可考虑嵌套结构。

答案 1 :(得分:0)

在第一个数组中创建一个新的数组和循环

$array1 = array('my_num' => 10, 'my_num2' => 20);
$array2 = array('my_num' => 15, 'my_num2' => 25);
$newArray = array();
foreach($array1 as $num => $one){
    if(isset($array2[$num])){
        $newArray[$num] = $one+$array2[$num];
    } else {
        $newArray[$num] = $one;
    }
}

print_r($newarray);

答案 2 :(得分:0)

在您的情况下,

$value是一个数组,而不是一个值。你可以试试这个:

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] = array();
            }

            foreach($value as $kk => $vv)
            {
                if ( ! isset($merged[$key][$kk]))
                {
                    $merged[$key][$kk] = $vv;
                }
                else
                {
                    $merged[$key][$kk] += $vv;
                }
            }
        }
    }
}