0

我有一个如下所示的数组(这是 $data 变量上的 print_r)

大批
(
    [0] => 数组
        (
            [权] => 1
            [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a
            [标题] => 扫帚柄 - 6" x 12.5"
            [总计] => 11.00
            [重量] => 0.25
            [图片] => thumb_37658989fcd29e9.jpg
        )

    [1] => 数组
        (
            [权] => 1
            [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a
            [标题] => 扫帚柄 - 6" x 12.5"
            [总计] => 11.00
            [重量] => 0.25
            [图片] => thumb_37658989fcd29e9.jpg
        )
    [2] => 数组
        (
            [权] => 1
            [prod_key] => of2ef85vb8333afaeec8cd51be30jq7i
            [标题] => 观看
            [总计] => 65.00
            [重量] => 0.15
            [图片] => thumb_37658989fcd29e9.jpg
        )
)

我要做的是遍历数组并将具有相同 prod_key 的项目组合成一个项目并更新总数、数量和重量,因此上面的示例应如下所示:

大批
(
    [0] => 数组
        (
            [权] => 2
            [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a
            [标题] => 扫帚柄 - 6" x 12.5"
            [总计] => 22.00
            [重量] => 0.50
            [图片] => thumb_37658989fcd29e9.jpg
        )
    [1] => 数组
        (
            [权] => 1
            [prod_key] => of2ef85vb8333afaeec8cd51be30jq7i
            [标题] => 观看
            [总计] => 65.00
            [重量] => 0.15
            [图片] => thumb_37658989fcd29e9.jpg
        )
)
4

1 回答 1

2

创建一个新数组并将产品密钥用作数组索引。然后您可以轻松添加或更新条目

$result = array();
foreach ($data as $v) {
    if (!isset($result[$v['prod_key']])) {
        $result[$v['prod_key']] = $v;
    } else {
    $result[$v['prod_key']]['quan'] += $v['quan'];
    $result[$v['prod_key']]['total'] += $v['total'];
    $result[$v['prod_key']]['weight'] += $v['weight'];
        //etc...
    }
}
于 2012-08-20T16:09:24.073 回答