php - How to sum (sub total) array based on two keys? -
i have array below values
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 ) )
and want sum array, first date , sku, want result below
array ( [2016-01-01] => array ( [rk101] => array ( [qty] => 7 ) [rk102] => array ( [qty] => 4 ) ) [2016-01-01] => array ( [rk101] => array ( [qty] => 4 ) ) )
i have explore stack overflow , found many post calculates sum based on 1 key, in case want sum array values based on date first , sku. please same
try below solution:
<?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 $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);
output:
array ( [2016-01-01] => array ( [rk101] => array ( [qty] => 7 ) [rk102] => array ( [qty] => 4 ) ) [2016-01-02] => array ( [rk101] => array ( [qty] => 4 ) ) )
Comments
Post a Comment