0

I have an array of arrays like this:

array('0'=> 
            array(
           'fromDate' =>2007,
           'toDate' => 2008,
           'value' => 7)
      '1'=>
            array(
            'fromDate' =>2010,
            'toDate' => ,
            'value' => 3)
      '2'=>
            array(
            'fromDate' => 2007,
            'toDate' => ,  
            'value' => 4))

I want to count 'value', add them up grouped by 'fromDate' like this:

array('0' =>
             array(
             'fromDate' => 2007,
             'sum' => 2)
      '1' =>
            array(
            'fromDate' => 2010,
            'sum' => 1))

Any help is much appreciated!

1
  • Can you be a bit more specific about what your requirement is ? Commented Apr 8, 2013 at 9:20

2 Answers 2

2
$myData = array('0'=>
            array(
           'fromDate' =>2007,
           'toDate' => 2008,
           'value' => 7),
      '1'=>
            array(
            'fromDate' =>2010,
            'toDate' => NULL,
            'value' => 3),
      '2'=>
            array(
            'fromDate' => 2007,
            'toDate' => NULL,
            'value' => 4)
);

$counts = array_reduce(
    $myData,
    function ($counter, $entry) {
        if (!isset($counter[$entry['fromDate']])) {
            $counter[$entry['fromDate']] = array(
                'fromDate' => $entry['fromDate'],
                'sum' => 1
            );
        } else {
            $counter[$entry['fromDate']]['sum']++;
        }
        return $counter;
    },
    array()
);

var_dump($counts);
Sign up to request clarification or add additional context in comments.

3 Comments

+1. Not a fan of array_reduce() but this answer makes good use of it :)
Thanks @Mark Baker! Now I need to understand why it works like a charm :) Any tips on where to best learn everything regarding arrays?
Best place to start (as always) is the php docs for array functions (php.net/manual/en/book.array.php); and the relevant pages on closures (php.net/manual/en/functions.anonymous.php) for using closures in callbacks
1

If you want to count how many arrays with "fromDate" e.g. 2007 you have:

function countByFromDate($array) {
  $result = array();
  foreach($array as $item) {
    $fromDate = $item['fromDate'];
    if (!isset($result[$fromDate])) {
      $result[$fromDate] = array('fromDate' => $fromDate, 'sum' => 0);  
    }
    $result[$fromDate]['sum']++;
  }

  return $result; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.