简体   繁体   English

当我想添加一些值时,如何合并两个2D php数组?

[英]How to merge two 2D php arrays while I want to add up some values?

I have two php arrays like these: 我有两个像这样的php数组:

Array
(
[0] => Array
    (
        [id] => 712
        [count] => 5
    )

[1] => Array
    (
        [id] => 5510
        [count] => 3
    )
)

Array
(
[0] => Array
    (
        [id] => 856
        [count] => 7
    )

[1] => Array
    (
        [id] => 5510
        [count] => 10
    )
)  

Now I want to make the merge result like this: 现在,我要像这样合并结果:

Array
(
[0] => Array
    (
        [id] => 712
        [count] => 5
    )

[1] => Array
    (
        [id] => 856
        [count] => 3
    )
[2] => Array
    (
        [id] => 5510
        [count] => 13
    )
)  

Just add the count up of those having the same id . 只需将具有相同idcount相加即可。
And of course the real array is much more complicated than the example above. 当然,实际数组比上面的示例复杂得多。

Can you show me a way to deal with this? 您能告诉我一种解决方法吗?

This should work for you 这应该为你工作

/**
 * merge counts for arrays
 * @param array $arrays,...
 * @return array
 */
function merge_counts(){

    $arrays = func_get_args();

    $ret = array();

    foreach($arrays as $arr){
        foreach($arr as $item){
            if(array_key_exists($k = $item['id'], $ret)){
                $ret[$k]['count'] += $item['count'];
            }
            else {
                $ret[$k] = $item;
            }
        }
    }

    return array_values($ret);   
}

Usage 用法

$result = merge_counts($one, $two);    
print_r($result);

// alternatively...
// $result = merge_counts($one, $two, $three, ...);

Output 产量

Array
(
    [0] => Array
        (
            [id] => 712
            [count] => 5
        )

    [1] => Array
        (
            [id] => 5510
            [count] => 13
        )

    [2] => Array
        (
            [id] => 856
            [count] => 7
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM