简体   繁体   中英

Counting values in multidimensional array to new array

I currently have the following array:

Array
(
[0] => Array
    (
        [declaration_value] => 1
        [date] => 2018-07-16
        [client_id] => 3
        [declaration_id] => 12
    )

[1] => Array
    (
        [declaration_value] => 3
        [date] => 2018-07-16
        [client_id] => 3
        [declaration_id] => 12
    )

)

how can i make to get the following array result: (count declaration_value if the same date/client_id/declaration_id )

Array
(
[0] => Array
    (
        [declaration_value] => 4
        [date] => 2018-07-16
        [client_id] => 3
        [declaration_id] => 12
    )
)
$listdb = [
        ["declaration_value" => 1, "date" => "2018-07-16", "client_id" => 3, "declaration_id" => 12],
        ["declaration_value" => 2, "date" => "2018-07-16", "client_id" => 2, "declaration_id" => 12],
        ["declaration_value" => 2, "date" => "2018-07-16", "client_id" => 2, "declaration_id" => 12],
        ["declaration_value" => 8, "date" => "2018-07-17", "client_id" => 2, "declaration_id" => 12],
        ["declaration_value" => 3, "date" => "2018-07-16", "client_id" => 3, "declaration_id" => 12],
    ];

    $sameKeys = ["date", "client_id", "declaration_id"];
    $sumKeys = ["declaration_value"];
    print_r(sum_my($listdb, $sameKeys, $sumKeys));

function sum_my(array $listdb = [], array $sameKeys = [], array $sumKeys = []): array {
    $newdb = [];
    if (empty($listdb) === true || empty($sameKeys) === true || empty($sumKeys) === true) {
        return $newdb;
    }

    foreach ($listdb as $value) {
        $ckKey = "";
        foreach ($sameKeys as $sameKey) {
            $ckKey .= $value[$sameKey];
        }
        if (isset($newdb[$ckKey])) {
            foreach ($sumKeys as $sumKey) {
                $newdb[$ckKey][$sumKey] += $value[$sumKey];
            }
        } else {
            $newdb[$ckKey] = $value;
        }
    }

    return $newdb;
}

Thank you for your tips, I solved it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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