0

我有一个这样的数组数组:

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

我想计算“价值”,将它们按“fromDate”分组,如下所示:

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

任何帮助深表感谢!

4

2 回答 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);
于 2013-04-08T09:39:18.333 回答
1

如果你想用“fromDate”计算有多少个数组,例如 2007,你有:

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; 
}
于 2013-04-08T09:42:16.227 回答