代码之家  ›  专栏  ›  技术社区  ›  Eryk Wróbel

按相同数组值计算多维数组值

  •  1
  • Eryk Wróbel  · 技术社区  · 7 年前

    假设这个场景。我们有这样的多维$产品阵列。2个产品,但每个产品有3个属性和不同的购物车数量。

    Array
    (
        [0] => Array
            (
                [id_product] => 1
                [id_product_attribute] => 5
                [cart_quantity] => 1
            )
        [1] => Array
            (
                [id_product] => 620
                [id_product_attribute] => 784
                [cart_quantity] => 8
            )
        [2] => Array
            (
                [id_product] => 1
                [id_product_attribute] => 12
                [cart_quantity] => 3
            )
    )
    

    如何将$product['cart U QUOTITY']中所有具有相同id U product的数组项相加,结果如下:

    Array
    (
         [1] => 4 // 1 + 3
         [620] => 8
    )
    

    我真的很抱歉的线程标题,我甚至不能形成什么我想实现不显示在上面的例子。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Barmar    7 年前

    使用简单的 foreach 循环。使用 $product['product_id'] 作为结果数组中的键,您只需在获得重复的ID时将其添加到结果数组中。

    $result = array();
    foreach ($products as $product) {
        $id = $product['product_id'];
        $quant = $product['cart_quantity'];
        if (isset($result[$id])) {
            $result[$id] += $quant;
        } else {
            $result[$id] = $quant;
    }
    
        2
  •  1
  •   Samir Sheikh    7 年前

    请尝试使用以下方式。。

    $totals = array();
    foreach ($main as $row) {
      $product = $row['id_product'];
      $quantity = $row['cart_quantity'];
      $totals[$product] += $quantity;
    }
    
    推荐文章