0

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?

1
  • Clarification: I can't edit the original foreach loop as it's used for something else, therefore how do I sort that data into an array that's useful for other stuff? Commented Jul 29, 2013 at 22:45

1 Answer 1

1

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'],
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately that just overwrites the data in the array as the customer could have more than one product in their basket from the same retailer.
Man this is why I love Stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.