我想采用以下数组并生成一个新数组,该数组将所有具有相同ID的相同键组合在一起,同时获取视图的SUM并仅获取最后一个DATE。
原始数组
Array (
[0] => Array (
[id] => 10
[views] => 276
[date] => 2012-01-30 10:55:00
[total] => N
)
[1] => Array (
[id] => 40
[views] => 287
[date] => 2012-01-27 10:00:29
[total] => Y
)
[2] => Array (
[id] => 40
[views] => 824
[date] => 2012-01-29 14:40:45
[total] => Y
)
[3] => Array (
[id] => 42
[views] => 723
[date] => 2012-01-28 20:15:58
[total] => N
)
[4] => Array (
[id] => 43
[views] => 428
[date] => 2012-01-28 17:14:31
[total] => N
)
[5] => Array (
[id] => 45
[views] => 174
[date] => 2012-01-20 18:01:11
[total] => N
)
)
新数组
Array (
[0] => Array (
[id] => 10
[views] => 276
[date] => 2012-01-30 10:55:00
[total] => N
)
[1] => Array (
[id] => 40
[views] => 1111
[date] => 2012-01-29 14:40:45
[total] => Y
)
[2] => Array (
[id] => 42
[views] => 723
[date] => 2012-01-28 20:15:58
[total] => N
)
[3] => Array (
[id] => 43
[views] => 428
[date] => 2012-01-28 17:14:31
[total] => N
)
[4] => Array (
[id] => 45
[views] => 174
[date] => 2012-01-20 18:01:11
[total] => N
)
)
答案 0 :(得分:0)
function last($a, $b) {
if (strtotime($a) > strtotime($b))
return $a;
else
return $b;
}
$new_array = array();
foreach ($original_array as $data) {
if (array_key_exists($data['id'], $new_array)) {
$new_array[$data['id']]['views'] += $data['views'];
$new_array[$data['id']]['date'] = last($new_array[$data['id']]['date'], $data['date']);
} else
$new_array[$data['id']] = $data;
}
$new_array = array_values($new_array);