PHP - Conditioned sum of some values of an array -


i have array in php of type, resulting particular query on db.

$output = array (   [0] => array        (        'price' => 100        'date' => '2015-07-28'        'total' => 200        'qty' => 2       )   [1] => array       (        'price' => 80        'date' => '2015-07-28'        'total' => 240        'qty' => 3       )   [2] => array       (        'price' => 100        'date' => '2015-07-29'        'total' => 300        'qty' => 3       )   [3] => array       (        'price' => 90        'date' => '2015-07-28'        'total' => 90        'qty' => 1       ) ) 

i'm trying sum total , qty based on price key values, obtaining array this:

$grouped = array ( [0] => array      (      [price] => 100      [sumtotal] => 500      [sumqty] => 5     )  [1] => array      (      [price] => 80      [sumtotal] => 240      [sumqty] => 3     )  [2] => array      (      [price] => 90      [sumtotal] => 90      [sumqty] => 1     )  ) 

still cannot find way around this.

try using simple foreach loop as

$result = array(); foreach ($output $key => $value) {     $hash = $value['price'];     if (isset($result[$hash])) {         $result[$hash]['price'] = $value['price'];         $result[$hash]['sumtotal'] += $value['total'];         $result[$hash]['sumqty'] += $value['qty'];     } else {         $result[$hash]['price'] = $value['price'];         $result[$hash]['sumtotal'] = $value['total'];         $result[$hash]['sumqty'] = $value['qty'];     } } print_r(array_values($result)); 

demo


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -