Skip to content
Advertisement

PHP Group Array values then sum

How can i group by adult price then get the sum of adult count. here is my array bellow:

    Array
        (
        [0] => Array
            (
                [Reservation] => Array
                    (
                        [adult_price] => 2000
                        [adult_count] => 2
                    )
            )

        [1] => Array
            (
                [Reservation] => Array
                    (
                        [adult_price] => 2000
                        [adult_count] => 1
                    )
            )

        [2] => Array
            (
                [Reservation] => Array
                    (
                        [adult_price] => 300
                        [adult_count] => 1
                    )
            )
    )

Expected Result if adult_price is same thats the time that the adult_count will add:

Array
    (
    [0] => Array
        (
            [Reservation] => Array
                (
                    [adult_price] => 2000
                    [adult_count] => 4
                )
        )

    [1] => Array
        (
            [Reservation] => Array
                (
                    [adult_price] => 300
                    [adult_count] => 1
                )
        )
)

Please help me thank you!

Advertisement

Answer

Try this:

$grouped = [];

foreach ($array as $item) {
    $item = $item["Reservation"];
    $currentValue = isset($grouped[$item["adult_price"]]) ? $grouped[$item["adult_price"]] : 0;
    $grouped[$item["adult_price"]] = $currentValue + $item["adult_count"];
}

$buildArray = [];

foreach ($grouped as $price => $count) {
    $buildArray[] = ["Reservation" => ["adult_price" => $price, "adult_count" => $count]];
}

print_r($buildArray);

https://3v4l.org/iZZ4m

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement