Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

sum of duplicates in array php

Im not sure what function to search for in regards to this so cant seem to help myself. Seems like an obvious problem really. I have an array, and where I have duplicate keys, I wish to add the values. e.g:

This is a section of my array.

[1] => Array
    (
        [inputAvg] => 21.41 KB
        [outputAvg] => 22.03 KB
        [date] => 2011-08-01
    )

[2] => Array
    (
        [inputAvg] => 182.63 KB
        [outputAvg] => 186.05 KB
        [date] => 2011-08-01
    )

[3] => Array
    (
        [inputAvg] => 182.63 KB
        [outputAvg] => 186.05 KB
        [date] => 2011-08-02
    )

[4] => Array
    (
        [inputAvg] => 4.84 MB
        [outputAvg] => 4.93 MB
        [date] => 2011-08-03
    )

All I wish to do is, say where the date key of the array is the same (e.g. here 2011-08-01) I want to show this date once, but with combined values of the duplicate item....?

e.g

[1] => Array
    (
        [inputAvg] => 204.04 KB
        [outputAvg] => 208.08 KB
        [date] => 2011-08-01
    )


[2] => Array
    (
        [inputAvg] => 182.63 KB
        [outputAvg] => 186.05 KB
        [date] => 2011-08-02
    )

[3] => Array
    (
        [inputAvg] => 4.84 MB
        [outputAvg] => 4.93 MB
        [date] => 2011-08-03
    )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?php

$array  = array(Array("inputAvg" => 21.41,"outputAvg" => 22.03,"date" => "2011-08-01"),
                Array("inputAvg" => 182.63,"outputAvg" => 186.05,"date" => "2011-08-01" ),
                Array("inputAvg" => 182.63, "outputAvg" => 186.05,"date" => "2011-08-02")
                );

$res  = array();
foreach($array as $vals){
    if(array_key_exists($vals['date'],$res)){
        $res[$vals['date']]['inputAvg']    += $vals['inputAvg'];
        $res[$vals['date']]['outputAvg']   += $vals['outputAvg'];
        $res[$vals['date']]['date']        = $vals['date'];
    }
    else{
        $res[$vals['date']]  = $vals;
    }
}

echo "<pre>";
print_r($res);

?>

Output :

Array
(
    [2011-08-01] => Array
        (
            [inputAvg] => 204.04
            [outputAvg] => 208.08
            [date] => 2011-08-01
        )

    [2011-08-02] => Array
        (
            [inputAvg] => 182.63
            [outputAvg] => 186.05
            [date] => 2011-08-02
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...