2013-07-29 180 views
0

我有一个foreach循环(返回购物车中产品的详细信息)。什么它的返回是这样的(我剪了下来一点):需要PHP数组操作帮助

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和内容是产品信息。任何想法如何诉诸这个阵列?

+0

说明:我不能编辑原始的foreach循环,因为它用于别的东西,因此如何将这些数据排序为对其他东西有用的数组? – ScottMcGready

回答

1

假设您发布的数组是$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'], 
); 
} 
+0

不幸的是,只是覆盖阵列中的数据,因为客户可能在同一零售商购买多个产品。 – ScottMcGready

+0

@ScottMcGready已经更新了这个问题 – AlexP

+0

男人这就是为什么我爱Stack。 – ScottMcGready