Search code examples
phpmenuiteminventory

Merge same items and add their quantity


I need help. How to code this in PHP? If I am using a form method to input item# and quantity

form method="post"<br />
input type="number" name="item1" | input type="number" name="quantity1"<br />
input type="number" name="item2" | input type="number" name="quantity2"<br />
input type="number" name="item3" | input type="number" name="quantity3"<br />

So, if I put same item# then the quantity will add their values. Thanks in advance.


Input: ( form method )
Item#: Quantity:
111 2
222 5
111 6
Output:
Item#: Quantity:
111 8
222 5

Solution

  • function group_items($string=""){
        if(!$string){return;}
        $grouped=array();
        preg_match_all('/([0-9\.]+(?: [0-9\.]+)?)/',$string,$matches);
        $string='';
        $matches = isset($matches[0])?$matches[0]:array();
        foreach($matches as $match){
            $exp = explode(' ',$match);
            if(!isset($grouped[$exp[0]])){
                $grouped[$exp[0]] = $exp[1];
            }else{
                $grouped[$exp[0]] += $exp[1];
            }
        }
        foreach($grouped as $key => $group){
            $string.=$key." ".$group." ";
        }
        return trim($string);
    }   
    

    calling it by:

    echo group_items("111 2 222 5 111 6");
    

    output:

     111 8 222 5