我有一个像:
这样的数组$arr[0] = ("1-3-2011","1","15"); //date(dd-mm-yyyy),id,amt
$arr[1] = ("1-4-2011","2","5");
$arr[2] = ("12-3-2011","6","20");
$arr[3] = ("1-3-2011","10","10");
$arr[4] = ("12-3-2011","3","10");
$arr[5] = ("1-4-2011","5","15");
$arr[6] = ("1-3-2011","7","15");
由此我需要生成像
这样的精简数组$newarr[0] = ("1-3-2011","1,7,10","40");
$newarr[0] = ("1-4-2011","2,5","20");
..
...
基本上第一个是多维数组,包含日期,ID和数量。在新数组中,我需要为每个唯一日期压缩前一个,将id作为重复日期的csv字符串和添加的数量。
最有效的方法是什么,性能明智?
答案 0 :(得分:0)
这样的事情应该这样做:
$newarr = array();
foreach($arr as $row) {
if(!isset($newarr[$row[0]])) {
$newarr[$row[0]] = array('ids' => array(), 'amount' => 0);
}
$newarr[$row[0]]['ids'][] = $row[1];
$newarr[$row[0]]['amount'] += $row[2];
}
foreach($newarr as $key => &$row) {
$row = array($key, implode(',', $row['ids']), $row['amount']);
} unset($row);
工作示例: