需要PHP数组操作帮助


PHP array manipulation help required

我有一个foreach循环(返回购物车中产品的详细信息)。它返回的是这个(我已经把它减少了一点):

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)
  }
}

我希望数组密钥是零售商ID,内容是产品信息。知道如何使用这个阵列吗?

假设您发布的数组是$data,这将为您提供一个关联数组,关键字是零售商id。

由于零售商不是唯一的,它将是一个或多个"产品"的阵列。

$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'],
  );
}