2015-04-22 25 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); 
相关问题