怎么可以组合日期和计算权重之和然后把关联数组php?
{name:"A",date:"2012-12-11",order:1,time:3,weight:10},
{name:"A",date:"2012-12-11",order:1,time:4,weight:12},
{name:"B",date:"2012-12-11",order:1,time:3,weight:17},
{name:"A",date:"2012-12-12",order:1,time:5,weight:50},
{name:"A",date:"2012-12-12",order:2,time:3,weight:70}
根据这个重量的总和,但是问题是(同一个日期相同的顺序同名;哪个更大的时间占用它的重量,不要小心)但不同的名称或顺序取组的总和。
结果必须如下:
{date:2012-12-11,weight:29},
{date:2012-12-12,weight:120},
任何帮助? 它可以像:
{name:"A",date:"2012-12-11",order:1,time:3,weight:10},
{name:"B",date:"2012-12-11",order:1,time:3,weight:17},
{name:"A",date:"2012-12-11",order:1,time:4,weight:12},
{name:"A",date:"2012-12-12",order:1,time:5,weight:50},
{name:"A",date:"2012-12-12",order:2,time:3,weight:70}
答案 0 :(得分:0)
我相信有一个更简单的解决方案,但我认为这就足够了:
$json = '[';
$json .= '{"name":"A","date":"2012-12-11","order":1,"time":3,"weight":10},';
$json .= '{"name":"A","date":"2012-12-11","order":1,"time":4,"weight":12},';
$json .= '{"name":"B","date":"2012-12-11","order":1,"time":3,"weight":17},';
$json .= '{"name":"A","date":"2012-12-12","order":1,"time":5,"weight":50},';
$json .= '{"name":"A","date":"2012-12-12","order":2,"time":3,"weight":70}]';
$orders = json_decode($json, true);
$result = array();
foreach ($orders as $row) {
$key = $row['date'].'.'.$row['order'].'.'.$row['time'];
$result[$key]['date'] = $row['date'];
if (isset($result[$key]['weight'])) {
if ($row['weight'] > $result[$key]['weight']) {
$result[$key]['weight'] = $row['weight'];
}
} else {
$result[$key]['weight'] = $row['weight'];
}
}
$realresult = array();
foreach ($result as $row) {
$realresult[$row['date']]['date'] = $row['date'];
if (isset($realresult[$row['date']]['weight'])) {
$realresult[$row['date']]['weight'] += $row['weight'];
} else {
$realresult[$row['date']]['weight'] = $row['weight'];
}
}
print_r($realresult);
//Array ( [2012-12-11] => Array ( [date] => 2012-12-11 [weight] => 29 ) [2012-12-12] => Array ( [date] => 2012-12-12 [weight] => 120 ) )
你可以在这里试试:http://codepad.viper-7.com/lSEhBC