2015-04-22 59 views
-3

如果產品ID相同,如何求和數組值?我需要總和product_price,quantity,total_price,shipping_price。這是我的例子如果product_id相同,如何求和數組值?

[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 
         ) 

       ) 
     ) 

我需要的結果是這樣的:

http://paste.ofcode.org/zeRZfLwDKj7btTtn2KSnmZ

+1

請分享所需的結果格式 –

+1

'for'循環將有所幫助。 –

+0

你可以使用PHP LINQ做選擇更新刪除操作請看https://phplinq.codeplex.com/wikipage?title=示例url for more info –

回答

0

您需要使用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); 
相關問題