【问题标题】:how to sum array values if product_id same?如果 product_id 相同,如何对数组值求和?
【发布时间】:2015-06-29 22:07:03
【问题描述】:

如果产品 id 相同,如何对数组值求和?我需要总和 product_price、数量、total_price、shipping_price。这是我的例子

[936] => Array
        (
            [order_number] => 936
            [status] => cancelled
            [products] => Array
                (
                    [0] => Array
                        (
                            [product_id] => 19
                            [sku] => sku2222222
                            [product_price] => 12.00
                            [quantity] => 1
                            [total_price] => 17
                            [shipping_price] => 5.00
                        )

                    [1] => Array
                        (
                            [product_id] => 19
                            [sku] => sku2222222
                            [product_price] => 12.00
                            [quantity] => 1
                            [total_price] => 17
                            [shipping_price] => 5.00
                        )

                    [2] => Array
                        (
                            [product_id] => 5
                            [sku] => sku2222222
                            [product_price] => 12.00
                            [quantity] => 1
                            [total_price] => 17
                            [shipping_price] => 5.00
                        )

                )
        )

【问题讨论】:

标签: php arrays


【解决方案1】:

您需要使用for 循环来汇总所有需要的变量。

$orders = array(
    936 => array(
        "order_number" => 936,
        "products" => array(
            array(
                "product_id" => 19,
                "total_price" => 17,
                "shipping_price" => 10
            ),
            array(
                "product_id" => 19,
                "total_price" => 17,
                "shipping_price" => 10
            ),
            array(
                "product_id" => 5,
                "total_price" => 17,
                "shipping_price" => 10
            ),
        )
    )
);

foreach ($orders as $order_id => $order) {
    $order_products = array();
    foreach ($order['products'] as $product) {
        if (isset($order_products[$product['product_id']])) {
            $order_products[$product['product_id']]['total_price'] += $product['total_price'];
            $order_products[$product['product_id']]['shipping_price'] += $product['shipping_price'];
        } else {
            $order_products[$product['product_id']] = $product;
        }
    }
    $orders[$order_id]['products'] = $order_products;
}

print_r($orders);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多