skip to Main Content

I have two arrays which have items and quantities and they are asociated by the index of the arrays. Example:

Items=XL,M,XL,S
Quantities=5,2,4,7

What I want to achieve is to remove the repetitive items and sum their quantities:

Items=XL,M,S
Quantities=9,2,7
    $uniqueTallesTotalesC = array_unique($tallesTotalesC);
    for($i=0;$i<Count($uniqueTallesTotalesC);$i++){
        for($e=0;$e<Count($cantidadesTotalesC);$e++){
            if($uniqueTallesTotalesC[$i]==$tallesTotalesC[$e] && $e > $i){
                $cantidadesTotalesC[$i] = $cantidadesTotalesC[$i] + $cantidadesTotalesC[$e];
            } else{
            }
        }
    }

2

Answers


  1. You can just blindly zip-merge them together with summation:

    $items      = explode(',', 'XL,M,XL,S');
    $quantities = explode(',', '5,2,4,7');
    
    if(count($items) !== count($quantities)){
        throw new RuntimeException('Count mismatch');
    }
    
    $final = [];
    for($i = 0; $i < count($items); $i++) {
        if(!isset($final[$items[$i]])){
            $final[$items[$i]] = 0;
        }
        $final[$items[$i]] += $quantities[$i];
    }
    
    var_dump($final);
    

    Outputs:

    array(3) {
      ["XL"]=>
      int(9)
      ["M"]=>
      int(2)
      ["S"]=>
      int(7)
    }
    

    Demo: https://3v4l.org/6A5ZC

    There’s probably an autovivification that I’m missing that could simplify this greater.

    Login or Signup to reply.
  2. I suggest you to create another array variable to hold the new items’ quantities:

    // I imagine these are your existing variables from your sample code
    $tallesTotalesC = array('XL','M','XL','S');
    $cantidadesTotalesC = array(5,2,4,7);
    
    $uniqueTallesTotalesC = array_unique($tallesTotalesC);
    // This will reset the indexes of the unique items array
    $uniqueTallesTotalesC = array_values($uniqueTallesTotalesC);
    
    // init a new quantities array with zeros
    $uniqueCantidadesTotales = array_fill(0, count($uniqueTallesTotalesC), 0);
    
    if (count($uniqueTallesTotalesC) == count($tallesTotalesC)) {
        // all items are unique so no need to loop through and sum the quantities
        $uniqueCantidadesTotales = $cantidadesTotalesC;
    } else {
        foreach($uniqueTallesTotalesC as $newIndex => $item) {
            // get all indexes of the item in the old array
            $oldIndexes = array_keys($tallesTotalesC, $item);
            // for each of the index, get the sum the old quantity to the new quantity
            foreach($oldIndexes as $oldIndex) {
                $uniqueCantidadesTotales[$newIndex] += $cantidadesTotalesC[$oldIndex];
            }
        }
    }
    

    Hope it helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search