php sum count并保留多维数组

时间:2016-11-29 07:36:18

标签: php

如何汇总多维数组并保留字段并添加求和字段。我想总结一下场数。

数组看起来像这样:

Array (
[0] => Array
    (
        [landingpage_id] => 5305bc90b7a6bb56478b4581
        [offer_id] => 9233440331d06b1f22dadb1641007585
        [count] => 5
    )

[2] => Array
    (

        [landingpage_id] => 5305bc90b7a6bb56478b4581
        [offer_id] => 53146a8bb7a6bb9b688b4567
        [count] => 3
    )

[4] => Array
    (
        [landingpage_id] => 5305bc90b7a6bb56478b4581
        [offer_id] => 53146a8bb7a6bb9b688b4567
        [count] => 2
    )
)

理想的结果是,因为它会将count字段与唯一的com:

相加
[0] => Array
    (
       [landingpage_id] => 5305bc90b7a6bb56478b4581
        [offer_id] => 9233440331d06b1f22dadb1641007585

        [count] => 5
    )



[1] => Array
    (
       [landingpage_id] => 5305bc90b7a6bb56478b4581
                [offer_id] => 53146a8bb7a6bb9b688b4567

        [count] => 5
    )

1 个答案:

答案 0 :(得分:0)

您可以使用array_reduce

$result = array_reduce($myArray, function ($carry, $item) {

    $key = $item['landingpage_id'] . $item['offer_id'];

    if (isset($carry[$key])) {
       $carry[$key]['count'] += $item['count'];
    } else {
       $carry[$key] = $item;
    }

    return $carry;

}, array());

$result = array_values($result); // this is needed only if you want to reset the keys of the resulted array