如果product_id相同,如何对数组值求和?

时间:2015-04-22 10:13:34

标签: php arrays

如果产品ID相同,如何对数组值求和?我需要总和product_price,quantity,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
                        )

                )
        )

1 个答案:

答案 0 :(得分:0)

您需要使用$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); 循环来汇总所有需要的变量。

var getFirstParagraph = "var paras = document.getElementsByTagName('p');" +
                        "console.log(paras[0].textContent);"

var urls = ["http://www.example.com", "http://www.example2.com"];
for(var i=0; i<urls.length; i++)
    {
pageWorker = require("sdk/page-worker").Page({
  contentScript: getFirstParagraph,
  contentURL : urls[i],
});
}