Aloong
Aloong

Reputation: 1725

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

I have two php arrays like these:

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.
And of course the real array is much more complicated than the example above.

Can you show me a way to deal with this?

Upvotes: 1

Views: 122

Answers (1)

maček
maček

Reputation: 77778

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
        )

)

Upvotes: 1

Related Questions