1

Possible Duplicate:
php how to group a multidimensional array by a particular value?
php group by SUM using multi dimensional array

I need some help in getting the count of the array element quantity by grouping it based on a date value part of a Multidimensional array in php

Here's my original array

Array
(
[0] => Array
    (
        [quantity] => 5
        [dd] => 01-Nov-2012
    )

[1] => Array
    (
        [quantity] => 10
        [dd] => 01-Nov-2012
    )

[2] => Array
    (
        [quantity] => 3
        [dd] => 02-Nov-2012
    )

[3] => Array
    (
        [quantity] => 4
        [dd] => 03-Nov-2012
    )

[3] => Array
    (
        [quantity] => 15
        [dd] => 03-Nov-2012
    )
)

And this is the Output I'm expecting

Array
(
[0] => Array
    (
        [quantity] => 15
        [dd] => 01-Nov-2012
    )

[1] => Array
    (
        [quantity] => 3
        [dd] => 02-Nov-2012
    )

[2] => Array
    (
        [quantity] => 19
        [dd] => 03-Nov-2012
    )
)
ekad
  • 13,718
  • 26
  • 42
  • 44
user15341
  • 19
  • 2
  • 3
    Have you tried anything? This doesn't seem difficult. – Passerby Nov 08 '12 at 06:59
  • possible duplicate of [php group by SUM using multi dimensional array](http://stackoverflow.com/q/5269188/), [Php Arrays Sum Group By](http://stackoverflow.com/q/11633176). See also [PHP - How to SUM and GROUP BY a multidimensional ARRAY by a key?](http://stackoverflow.com/q/2827501/). – outis Nov 08 '12 at 17:59
  • ... dup of [php array group by using day,month and year](http://stackoverflow.com/q/5272953/), [Collating multidimensional array values](http://stackoverflow.com/q/6276001). – outis Nov 08 '12 at 18:09

2 Answers2

2

Just loop trough the rows, and add up the quantities in a different array indexed by the dd values.

$in = array(array()); // your input
$out = array();
foreach ($in as $row) {
    if (!isset($out[$row['dd']])) {
        $out[$row['dd']] = array(
            'dd' => $row['dd'],
            'quantity' => 0,
        );
    }
    $out[$row['dd']]['quantity'] += $row['quantity'];
}
$out = array_values($out); // make the out array numerically indexed
var_dump($out);
complex857
  • 19,129
  • 6
  • 44
  • 50
1

Orrrrr... Since the days are unique:

  <?php

  header('Content-type: text/plain');

  $inputArray  = array(
    array('qty' => 5,  'dd'  => '01-Nov-2012'),
    array('qty' => 10, 'dd'  => '01-Nov-2012'),
    array('qty' => 3,  'dd'  => '02-Nov-2012'),
    array('qty' => 4,  'dd'  => '03-Nov-2012'),
    array('qty' => 15, 'dd'  => '03-Nov-2012'));

  $outputArray = array();

  foreach ( $inputArray as $record ) {
    if ( !key_exists($record['dd'], $outputArray) ) {
      $outputArray[$record['dd']] = 0;
    }
    $outputArray[$record['dd']] += $record['qty'];
  }

  print_r($outputArray);

would produce:

Array
(
    [01-Nov-2012] => 15
    [02-Nov-2012] => 3
    [03-Nov-2012] => 19
)
Ariaan
  • 1,096
  • 1
  • 9
  • 13