ScottMcGready
ScottMcGready

Reputation: 1622

PHP array manipulation help required

I've got a foreach loop (returning the details of products in the cart). What it's returning is this (I've cut it down a bit):

array(2) {
  [0]=>
  array(4) {
    ["retailer"]=>
    string(1) "2"
    ["productid"]=>
    int(400)
    ["quantity"]=>
    string(1) "1"
    ["discount"]=>
    int(0)
  }
  [1]=>
  array(4) {
    ["retailer"]=>
    string(1) "2"
    ["productid"]=>
    int(470)
    ["quantity"]=>
    int(1)
    ["discount"]=>
    int(0)
  }
}

What I'd like is for the array key to be the retailer ID and the content to be the product information. Any idea how to resort this array?

Upvotes: 0

Views: 39

Answers (1)

AlexP
AlexP

Reputation: 9857

Assuming the array you posted is $data, this will give you an associative array with the key being the retailer id.

As the retailer is non unique, it will be an array of one or more "products".

$result = array();
foreach ($data as $row) {

  $id = $row['retailer'];  
  if (! isset($result[$id])) $result[$id] = array();

  $result[$id][] = array(
    'productid' => $row['productid'],
    'quantity'  => $row['quantity'],
    'discount'  => $row['discount'],
  );
}

Upvotes: 1

Related Questions