SUM value in array PHP

Sadu

New Member
#1
I have a problem with array. I want to sum up the given quantities (qty).
I want to get:
blyszczaca Normal = 6;
czapkoszal Normal = 6;
czapkoszal Luxury = 2;
etola Wolf = 1;
etola Normal = 2;
from this array. Can you help me please? I think about it for the last 4 hours and nothing. Still learning.
Mã:
Array
(
    [0] => Array
        (
            [produkt] => blyszczaca
            [model] => Normal
            [price] => 27.00
            [qty] => 2
        )

    [1] => Array
        (
            [0] => blyszczaca
            [1] => Normal
            [2] => 27.00
            [3] => 2
        )

    [2] => Array
        (
            [0] => blyszczaca
            [1] => Normal
            [2] => 27.00
            [3] => 2
        )

    [3] => Array
        (
            [0] => czapkoszal
            [1] => Normal
            [2] => 41.00
            [3] => 2
        )

    [4] => Array
        (
            [0] => czapkoszal
            [1] => Luxury
            [2] => 45.00
            [3] => 2
        )


    [5] => Array
        (
            [0] => czapkoszal
            [1] => Normal
            [2] => 41.00
            [3] => 2
        )

    [6] => Array
        (
            [0] => czapkoszal
            [1] => Normal
            [2] => 41.00
            [3] => 1
        )

    [7] => Array
        (
            [0] => czapkoszal
            [1] => Normal
            [2] => 41.00
            [3] => 1
        )

    [8] => Array
        (
            [0] => etola
            [1] => Wolf
            [2] => 47.00
            [3] => 1
        )

    [9] => Array
        (
            [0] => etola
            [1] => Normal
            [2] => 39.00
            [3] => 1
        )

    [10] => Array
        (
            [0] => etola
            [1] => Normal
            [2] => 39.00
            [3] => 1
        )

)
Thank you.
 

Admin

Administrator
Thành viên BQT
#2
You should create new array with unique keys and count quantities, for example:
Mã:
$sums = [];
foreach ($your_array as $item) {
    // create a unique key as concatenation of `product` and `model`
    $key = $item['product'] . ':' . $item['model'];

    // check if such key exists, if not - init key with `0`
    if (!isset($sums[$key])) {
        $sums[$key] = 0;
    }

    // add current `qty` to the value of `$sums[$key]`
    $sums[$key] += $item['qty']
}
 
Top