如何通过检查另一个键的数组值的重复来总结一个键的数组值

时间:2012-06-29 13:50:21

标签: php arrays multidimensional-array

Array
(
    [0] => Array
        (
            [linkId] => 1
            [clicksDate] => 1340856000
            [clicksCount] => 1
        )

    [1] => Array
        (
            [linkId] => 1
            [clicksDate] => 1340942400
            [clicksCount] => 2
        )

    [2] => Array
        (
            [linkId] => 1
            [clicksDate] => 1340942400
            [clicksCount] => 1
        )

    [3] => Array
        (
            [linkId] => 2
            [clicksDate] => 1340856000
            [clicksCount] => 2
        )

    [4] => Array
        (
            [linkId] => 2
            [clicksDate] => 1340942400
            [clicksCount] => 3
        )

    [5] => Array
        (
            [linkId] => 2
            [clicksDate] => 1340942400
            [clicksCount] => 1
        )

    [6] => Array
        (
            [linkId] => 3
            [clicksDate] => 1340856000
            [clicksCount] => 0
        )
}

输出:

Array(

    [0] => Array(  
       [clicksDate] => 1340856000,
       [clicksCount] => 3
     )

    [1] => Array(  
       [clicksDate] => 1340942400,
       [clicksCount] => 7
     )
)

第一个数组有两个相似的日期,基于日期重复,我需要总结点击次数。任何人都可以帮我找到简单的解决方案吗?

1 个答案:

答案 0 :(得分:4)

您可以将日期设置为关联数组的键,然后将点击数加总为值,如下所示:

$result = array();
foreach ($data as $value) {
    if (!isset($result[$value['clicksDate']])) {
        $result[$value['clicksDate']] = 0;
    }
    $result[$value['clicksDate']] += $value['clicksCount'];
}
var_dump($result);

在此处查看此行动:http://codepad.org/tJEBTobr