如何通过对合并值进行求和来合并两个数组[重复]

时间:2022-05-02 08:24:45

Possible Duplicate:
PHP: How to sum values of the array of the same key

可能重复:PHP:如何对相同键的数组的值求和

I am looking for an array_merge() function that does NOT replace values, but ADDS them.

我正在寻找一个不替换值的array_merge()函数,但ADDS它们。

Example, this is the code I am trying:

例如,这是我正在尝试的代码:

    echo "<pre>"; 

    $a1 = array(
         "a" => 2
        ,"b" => 0
        ,"c" => 5
    );

    $a2 = array(
         "a" => 3
        ,"b" => 9
        ,"c" => 7
        ,"d" => 10
    );

    $a3 = array_merge($a1, $a2);
    print_r($a3); 

Sadly, this outputs this:

可悲的是,这输出了这个:

Array
(
    [a] => 3
    [b] => 9
    [c] => 7
    [d] => 10
)

I then tried, instead of array_merge, just simply adding the two arrays

然后我试着,而不是array_merge,只是简单地添加两个数组

$a3 = $a1 + $a2;

But this outputs

但这输出

Array
(
    [a] => 2
    [b] => 0
    [c] => 5
    [d] => 10
)

What I truly want is to be able to pass as many arrays as needed, and then get their sum. So in my example, I want the output to be:

我真正想要的是能够根据需要传递尽可能多的数组,然后得到它们的总和。所以在我的例子中,我希望输出为:

Array
(
    [a] => 5
    [b] => 9
    [c] => 12
    [d] => 10
)

Of course I can schlepp and build some function with many foreach etc, but am looking or a smarter, cleaner solution. Thanks for any pointers!

当然,我可以schlepp和许多foreach等建立一些功能,但我正在寻找或更聪明,更清洁的解决方案。感谢您的任何指示!

4 个解决方案

#1


46  

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0);
}

You could shorten this to the following using the error suppression operator, but it should be considered ugly:

您可以使用错误抑制运算符将此缩短为以下内容,但应将其视为丑陋:

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = @($a1[$key] + $a2[$key]);
}

Alternatively, some mapping:

或者,一些映射:

$keys = array_fill_keys(array_keys($a1 + $a2), 0);
$sums = array_map(function ($a1, $a2) { return $a1 + $a2; }, array_merge($keys, $a1), array_merge($keys, $a2));

Or sort of a combination of both solutions:

或者两种解决方案的组合:

$sums = array_fill_keys(array_keys($a1 + $a2), 0);
array_walk($sums, function (&$value, $key, $arrs) { $value = @($arrs[0][$key] + $arrs[1][$key]); }, array($a1, $a2));

I think these are concise enough to adapt one of them on the spot whenever needed, but to put it in terms of a function that accepts an unlimited number of arrays and sums them:

我认为这些足够简洁,可以根据需要在现场调整其中一个,但是根据接受无限数量的数组并对它们求和的函数来说:

function array_sum_identical_keys() {
    $arrays = func_get_args();
    $keys = array_keys(array_reduce($arrays, function ($keys, $arr) { return $keys + $arr; }, array()));
    $sums = array();

    foreach ($keys as $key) {
        $sums[$key] = array_reduce($arrays, function ($sum, $arr) use ($key) { return $sum + @$arr[$key]; });
    }
    return $sums;
}

#2


9  

My contribution:

我的贡献:

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

Pass as many arrays to it as you want. Feel free to add some more defense, ability to accept multidimensional arrays, or type checking.

根据需要将尽可能多的数组传递给它。随意添加一些防御,接受多维数组或类型检查的能力。

Demo: http://codepad.org/JG6zwAap

演示:http://codepad.org/JG6zwAap

#3


3  

its not so complicate do something like:

它不那么复杂做类似的事情:

$a3 = $a1;

foreach($a2 as $k => $v) {
    if(array_key_exists($k, $a3)) {
       $a3[$k] += $v;
    } else {
       $a3[$k] = $v; 
    }
}

#4


-4  

You can use array_push function.I hope it will help you

你可以使用array_push函数。我希望它能帮到你

foreach($a2 as $a2){
    array_push($a1, $a2);
    }

    print_r($a1);

Output:

Array
(
    [a] => 2
    [b] => 0
    [c] => 5
    [0] => 3
    [1] => 9
    [2] => 7
    [3] => 10
)

OR you can change your logic in key value with numbers.It works even it have same number as follows:

或者您可以使用数字更改键值中的逻辑。它甚至可以使用相同的数字,如下所示:

<?php
$beginning = array(1 => 'foo');
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

Output:

Array (
 [0] => foo
 [1] => bar
 )

Enjoy!!!!!!!!!!!!!!

请享用!!!!!!!!!!!!!!

#1


46  

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0);
}

You could shorten this to the following using the error suppression operator, but it should be considered ugly:

您可以使用错误抑制运算符将此缩短为以下内容,但应将其视为丑陋:

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = @($a1[$key] + $a2[$key]);
}

Alternatively, some mapping:

或者,一些映射:

$keys = array_fill_keys(array_keys($a1 + $a2), 0);
$sums = array_map(function ($a1, $a2) { return $a1 + $a2; }, array_merge($keys, $a1), array_merge($keys, $a2));

Or sort of a combination of both solutions:

或者两种解决方案的组合:

$sums = array_fill_keys(array_keys($a1 + $a2), 0);
array_walk($sums, function (&$value, $key, $arrs) { $value = @($arrs[0][$key] + $arrs[1][$key]); }, array($a1, $a2));

I think these are concise enough to adapt one of them on the spot whenever needed, but to put it in terms of a function that accepts an unlimited number of arrays and sums them:

我认为这些足够简洁,可以根据需要在现场调整其中一个,但是根据接受无限数量的数组并对它们求和的函数来说:

function array_sum_identical_keys() {
    $arrays = func_get_args();
    $keys = array_keys(array_reduce($arrays, function ($keys, $arr) { return $keys + $arr; }, array()));
    $sums = array();

    foreach ($keys as $key) {
        $sums[$key] = array_reduce($arrays, function ($sum, $arr) use ($key) { return $sum + @$arr[$key]; });
    }
    return $sums;
}

#2


9  

My contribution:

我的贡献:

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

Pass as many arrays to it as you want. Feel free to add some more defense, ability to accept multidimensional arrays, or type checking.

根据需要将尽可能多的数组传递给它。随意添加一些防御,接受多维数组或类型检查的能力。

Demo: http://codepad.org/JG6zwAap

演示:http://codepad.org/JG6zwAap

#3


3  

its not so complicate do something like:

它不那么复杂做类似的事情:

$a3 = $a1;

foreach($a2 as $k => $v) {
    if(array_key_exists($k, $a3)) {
       $a3[$k] += $v;
    } else {
       $a3[$k] = $v; 
    }
}

#4


-4  

You can use array_push function.I hope it will help you

你可以使用array_push函数。我希望它能帮到你

foreach($a2 as $a2){
    array_push($a1, $a2);
    }

    print_r($a1);

Output:

Array
(
    [a] => 2
    [b] => 0
    [c] => 5
    [0] => 3
    [1] => 9
    [2] => 7
    [3] => 10
)

OR you can change your logic in key value with numbers.It works even it have same number as follows:

或者您可以使用数字更改键值中的逻辑。它甚至可以使用相同的数字,如下所示:

<?php
$beginning = array(1 => 'foo');
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

Output:

Array (
 [0] => foo
 [1] => bar
 )

Enjoy!!!!!!!!!!!!!!

请享用!!!!!!!!!!!!!!