2

这是我的数组:

Array ( 
[0] => Array ( [date] => 28-10-2012 [total] => 100 [earn] => 10 ) 
[1] => Array ( [date] => 28-12-2012 [total] => 100 [earn] => 10 ) 
[2] => Array ( [date] => 28-12-2012 [total] => 90 [earn] => 9 ) 
[3] => Array ( [date] => 28-12-2012 [total] => 315.35 [earn] => 31.535 ) 
[4] => Array ( [date] => 02-01-2013 [total] => 1500 [earn] => 150 ) 
[5] => Array ( [date] => 02-01-2013 [total] => 1000 [earn] => 100 ) 
)

愿望输出:

Array ( 
 [0] => Array ( [date] => 28-10-2012 [total] => 100 [earn] => 10 ) 
 [1] => Array ( [date] => 28-12-2012 [total] => 505.35 [earn] => 505.535 ) 
 [2] => Array ( [date] => 02-01-2013 [total] => 2500 [earn] => 250 )  
)

到目前为止,我尝试的方法设法按日期分组,并且只用两个不同的数组总结一个字段。

Array ( [28-10-2012] => 100 [28-12-2012] => 505.535 [02-01-2013] => 2500)

Array ( [28-10-2012] => 10 [28-12-2012] => 50.535 [02-01-2013] => 250 )

这与我正在寻找的非常不同,仍然让我头疼。有什么可能的方法??

4

2 回答 2

2

我认为没有内置函数,您必须自己编写算法。像这样的东西:

$result = array();
foreach ($array as $row)
{
  $result[$row['date']]['date'] = $row['date'];
  $result[$row['date']]['total'] += $row['total'];
  $result[$row['date']]['earn'] += $row['earn'];
}
$result = array_values($result);
于 2013-01-04T02:34:43.837 回答
0

这是总结数组中字段的一种方法。

这与之前的答案基本相同,但您应该检查密钥的存在,因为您将在每个唯一日期的第一次访问时获得“未定义索引”。希望这可以帮助。

        // your example input array
        $arr = array(
            array( 'date'=>'28-10-2012', 'total'=>100, 'earn'=>10 ),
            array( 'date'=>'28-10-2012', 'total'=>100, 'earn'=>12 ),
            array( 'date'=>'28-11-2012', 'total'=>120, 'earn'=>12 ),

        );

        $newData = array();
        foreach($arr as $row) {
            if(array_key_exists( $row['date'], $newData)) {
                $newData[$row['date']]['total'] += $row['total'];
                $newData[$row['date']]['earn'] += $row['earn'];         
            } else {
                $newData[$row['date']] = $row;
            }
        }
于 2013-01-04T02:46:29.440 回答