phparraysmultidimensional-arraysumgrouping

Group rows of a multidimensional array by one column and sum another column of values within each group


I have an numbered array like this in PHP

Original array:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [2] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [3] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )
                    [4] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

        )

I want it to group the same "id" and add up quantity if there are duplicates, If the "id" is the key instead of numbered keys, I should be able to do it.

What I expected the results is:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 10
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 10
                        )

                    [2] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

        )

Solution

  • Working Solution

    <?php 
    $your_arr = array(
        array('id' => 1,'qty' => 5),
        array('id' => 2,'qty' => 5),
        array('id' => 2222,'qty' => 5),
        array('id' => 1,'qty' => 5),
        array('id' => 3,'qty' => 5)
    );
    $new = array();
    foreach ($your_array as $r){
        if(!isset($new[$r['id']]))$t=0; //check the current id exist in $new if Not $t = 0; 
        else $t=$r['qty']; //if yes $t's value become the saved value in $new[$r['id']]
        $new[$r['id']]['id'] = $r['id'];
        $new[$r['id']]['qty'] = ($t+$r['qty']); // add the new value with $new[$r['id]]'s value.
    
    }
    echo "<pre>";print_r($new);
    ?>