2016-02-08 39 views
3

我有陣列具有低於值如何基於兩個鍵求和(小計)數組?

Array 
(
    [0] => Array 
     (
      [order_date] => 2016-01-01 
      [sku] => RK101 
      [qty] => 2 
     ) 

    [1] => Array 
     (
      [order_date] => 2016-01-01 
      [sku] => RK101 
      [qty] => 5 
     ) 

    [2] => Array 
     (
      [order_date] => 2016-01-01 
      [sku] => RK102 
      [qty] => 4 
     ) 

    [3] => Array 
     (
      [order_date] => 2016-01-02 
      [sku] => RK101 
      [qty] => 2 
     ) 

    [4] => Array 
     (
      [order_date] => 2016-01-02 
      [sku] => RK101 
      [qty] => 2 
     ) 
) 

,我想求和陣列,首先由日期,然後按SKU,我想導致像下面

Array 
(
    [2016-01-01] => Array 
    (
     [RK101] => Array 
     (
      [qty] => 7 
     ) 
     [RK102] => Array 
     (
      [qty] => 4 
     ) 
    ) 
    [2016-01-01] => Array 
    (
     [RK101] => Array 
     (
      [qty] => 4 
     ) 
    ) 
) 

我有探索堆棧溢出,並發現許多帖子計算基於一個關鍵的總和,在這種情況下,我想總結基於日期的數組值,然後通過sku。 請用相同

回答

3

嘗試以下解決方案幫助:

<?php 
echo '<pre>'; 

$array = Array 
(
    '0' => Array 
    (
     'order_date' => '2016-01-01', 
     'sku' => 'RK101', 
     'qty' => 2 
    ), 

    '1' => Array 
    (
     'order_date' => '2016-01-01', 
     'sku' => 'RK101', 
     'qty' => 5 
    ), 

    '2' => Array 
    (
     'order_date' => '2016-01-01', 
     'sku' => 'RK102', 
     'qty' => 4 
    ), 

    '3' => Array 
    (
     'order_date' => '2016-01-02', 
     'sku' => 'RK101', 
     'qty' => 2 
    ), 

    '4' => Array 
    (
     'order_date' => '2016-01-02', 
     'sku' => 'RK101', 
     'qty' => 2 
    ) 
); 

$new_array = array(); 
foreach ($array as $a) { 
    if (!isset($new_array[$a['order_date']][$a['sku']]['qty'])) { 
     $new_array[$a['order_date']][$a['sku']]['qty'] = 0; 
    } 
    $new_array[$a['order_date']][$a['sku']]['qty'] += $a['qty']; 
} 

print_r($new_array); 

輸出:

Array 
(
    [2016-01-01] => Array 
     (
      [RK101] => Array 
       (
        [qty] => 7 
       ) 

      [RK102] => Array 
       (
        [qty] => 4 
       ) 

     ) 

    [2016-01-02] => Array 
     (
      [RK101] => Array 
       (
        [qty] => 4 
       ) 

     ) 

) 
+0

謝謝bhai @chetan,它的工作 – Manoj

0

這裏是另一個解決方案,讓您有一個稍微不同的輸出,這可能是也可能不是首選。

$results = array(); 

$myNums = array(
    array(
     'order_date' => '2016-01-01', 
     'sku' => 'RK101', 
     'qty' => 2, 
    ), 
    array(
     'order_date' => '2016-01-01', 
     'sku' => 'RK101', 
     'qty' => 1, 
    ), 
    array(
     'order_date' => '2016-01-02', 
     'sku' => 'RK101', 
     'qty' => 2, 
    ), 
); 

foreach ($myNums as $num) { 
    $key = "{$num['order_date']}|{$num['sku']}"; 
    if (! array_key_exists($key, $results)) { 
     $results[$key] = 0; 
    } 
    $results[$key] += $num['qty']; 
} 

var_dump($results); 
/* 
var_dump gives the following... 
Array 
(
    [2016-01-01|RK101] => 3, 
    [2016-01-02|RK101] => 2, 
)*/