user2946343
user2946343

Reputation: 3

merging a multidimensional array PHP

Sorry if this is a duplicate but I tried my hardest to find a similar question but I wasn't 100% sure what exactly to search for.

The array below is from an e-commerce site I am creating. Each item has colour variants with a unique item code, however items share a sku. I would like to merge the array by the sku code to calculate the quantity of each item. I have seen ways to merge arrays with the same key but can't find a way to merge these.

Thanks

array(4) {
  ["ITEM-CHAIR-v-V0002"]=>
  array(4) {
    ["itemcode"]=> string(16) "ITEM-CHAIR-v-V0002"
    ["sku"]=>string(8) "ITEM-CHAIR"
    ["quantity"]=>string(1) "4"
    ["price"]=>string(5) "49.99"
   }
 ["ITEM-CHAIR-v-V0003"]=>
 array(4) {
    ["itemcode"]=>string(16) "ITEM-CHAIR-v-V0003"
    ["sku"]=>string(8) "ITEM-CHAIR"
    ["quantity"]=>string(1) "7"
    ["price"]=>string(5) "49.99"
   }
 ["ITEM-KNIFE-v-V0001"]=>
 array(4) {
    ["itemcode"]=>string(22) "ITEM-KNIFE-v-V0001"
    ["sku"]=>string(14) "ITEM-KNIFE"
    ["quantity"]=>string(1) "1"
    ["price"]=>string(5) "45.00"
   }
 ["ITEM-CHAIR-v-V0001"]=>
 array(4) {
    ["itemcode"]=>string(16) "ITEM-CHAIR-v-V0001"
    ["sku"]=>string(8) "ITEM-CHAIR"
    ["quantity"]=>string(1) "4"
    ["price"]=>string(5) "49.99"
  }
}

Upvotes: 0

Views: 41

Answers (2)

Andrey Sudiev
Andrey Sudiev

Reputation: 1

As I understand.

 $resultArray = [];
    foreach ($entryArray as $value){
        $resultArray[$value["sku"]][$value["itemcode"]]=$value;
    } 

Now you get that:

array(2) {
    ["ITEM-CHAIR"]=>{
         array(3){
             ["ITEM-CHAIR-v-V0003"] => array(4){...}
             ["ITEM-CHAIR-v-V0002"] => array(4){...}
             ["ITEM-CHAIR-v-V0001"] => array(4){...}
         }
    }
    ["ITEM-KNIFE"]=>{
         array(1){
              ["ITEM-KNIFE-v-V0001"] => array(4){...}
         }     
    }
}

Maybe you want this. So you can use count($resultArray["ITEM-X"]) to get count of sku. And you also get a better sorted array of your products.

Upvotes: 0

marian0
marian0

Reputation: 3327

Iterate over your array and just increment array with current counters if you found that key exist or create new index:

$results = array();
foreach ($inputArray as $item) {
    if (isset($results[$item['sku']])) {
        ++$results[$item['sku']];
    } else {
        $results[$item['sku']] = 1;
    }
}

Upvotes: 2

Related Questions