有这么一个需求,需要把多条数据合并为一条。
$data = array();
$data[] = array("id" => "123", "name" => "money", "before_save" => "10", "after_save" => "20", "create_date" => "2014-10-23");
$data[] = array("id" => "123", "name" => "money", "before_save" => "20", "after_save" => "30", "create_date" => "2014-10-24");
$data[] = array("id" => "123", "name" => "money", "before_save" => "30", "after_save" => "50", "create_date" => "2014-10-25");
$data[] = array("id" => "123", "name" => "duration", "before_save" => "10", "after_save" => "20", "create_date" => "2014-10-23");
$data[] = array("id" => "123", "name" => "duration", "before_save" => "20", "after_save" => "30", "create_date" => "2014-10-24");
$data[] = array("id" => "456", "name" => "money", "before_save" => "60", "after_save" => "70", "create_date" => "2014-10-26");
$data[] = array("id" => "456", "name" => "money", "before_save" => "70", "after_save" => "80", "create_date" => "2014-10-27");
$data[] = array("id" => "456", "name" => "money", "before_save" => "80", "after_save" => "100", "create_date" => "2014-10-28");
$data[] = array("id" => "456", "name" => "duration", "before_save" => "60", "after_save" => "70", "create_date" => "2014-10-26");
$data[] = array("id" => "456", "name" => "duration", "before_save" => "70", "after_save" => "80", "create_date" => "2014-10-27");
$data[] = array("id" => "456", "name" => "duration", "before_save" => "80", "after_save" => "100", "create_date" => "2014-10-28");
将上面id和name相同的合并为一条数据。
合并规则是:
before_save的值为create_date最小的那一条的before_save值
after_save的值为create_date最大的那一条的after_save值
create_date的值取最大值
例如前三条数据得出结果需要为
$data[] = array("id" => "123", "name" => "money", "before_save" => "10", "after_save" => "50", "create_date" => "2014-10-25");
上面结果一共会得出4条数据,分别是
$returndata[0] = array("id" => "123", "name" => "money", "before_save" => "10", "after_save" => "50", "create_date" => "2014-10-25");
$returndata[1] = array("id" => "123", "name" => "duration", "before_save" => "10", "after_save" => "30", "create_date" => "2014-10-24");
$returndata[2] = array("id" => "456", "name" => "money", "before_save" => "60", "after_save" => "100", "create_date" => "2014-10-28");
$returndata[3] = array("id" => "456", "name" => "duration", "before_save" => "60", "after_save" => "100", "create_date" => "2014-10-28");
小弟刚学php没多久,不太熟悉,求大神帮忙
------解决思路----------------------
$res = array();
foreach($data as $t) $res[$t['id']][$t['name']][$t['create_date']] = $t;
$returndata = array();
foreach($res as $t) {
foreach($t as $r) {
ksort($r);
$v = array_pop($r);
$p = array_shift($r);
$v['before_save'] = $p['before_save'];
$returndata[] = $v;
}
}
print_r($returndata);