Nigel Nigel - 1 year ago 64
PHP Question

how to add 'item_qty' if the 'item_id' matches, and store the new result in an array?

$arr = array(
0 => array('item_id' => 13,
'item_qty' => 3,
),
1 => array('item_id' => 10,
'item_qty' => 7,
),
2 => array('item_id' => 13,
'item_qty' => 2,
),
3 => array('item_id' => 10,
'item_qty' => 4,
),
4 => array('item_id' => 10,
'item_qty' => 4,
),
);


how to add
item_qty
if the
item_id
matches, and store the new result in an array?

Answer Source

I think this is what you need . loop the array and set item_id as key to new array and check if already item_id is set add the quantity like this .

    <?php

    $arr = array ( 0 => array ( 'item_id' => 13 , 'item_qty' => 3 ), 
                  1 => array ( 'item_id' => 10 , 'item_qty' => 7 ),
                  2 => array ( 'item_id' => 13, 'item_qty' => 2 ), 
                  3 => array ( 'item_id' => 10 ,'item_qty' => 4 ), 
                  4 => array ( 'item_id' => 10 ,'item_qty' => 4 ));

    $new_array =array();

    foreach($arr as $key=>$row)
    {

       $new_array[$row['item_id']]=isset($new_array[$row['item_id']])? array('item_id'=>$row['item_id'],'item_qty'=>$row['item_qty']+$new_array[$row['item_id']]['item_qty']) : $row;   
    }

    echo "<pre>";
    print_r($new_array);

    ?>

Output :

    Array
    (
        [13] => Array
            (
                [item_id] => 13
                [item_qty] => 5
            )

        [10] => Array
            (
                [item_id] => 10
                [item_qty] => 15
            )

    )

Update 1

Use array_values to reset the array key.

        Array
        (
            [0] => Array
                (
                    [item_id] => 13
                    [item_qty] => 5
                )

            [1] => Array
                (
                    [item_id] => 10
                    [item_qty] => 15
                )

        )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download