Php组数据思想
如何将分组日期和计算权重之和放入assoc数组phpPhp组数据思想,php,arrays,json,sorting,grouping,Php,Arrays,Json,Sorting,Grouping,如何将分组日期和计算权重之和放入assoc数组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}, {na
{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}
你需要两样东西:
以及:
…其中,sortfcn
是一个字符串,带有用于排序的自定义函数的名称:
function sortfcn($a, $b) {
if ($a['date'] > $b['date') { return 1; }
else if ($a['date'] < $b['date']) { return -1; }
return 0;
}
函数sortfcn($a,$b){
如果($a['date']>$b['date'){return 1;}
else if($a['date']<$b['date']){return-1;}
返回0;
}
我还没有测试这些,但这是主要的想法,看看文档,以清除我的语法错误,并得到更好的想法。它肯定会做你想要的
对权重求和是一个简单的问题,每个人都要通过排序后的数组进行求和。但是如果名称和顺序相同,我们会关心时间的权重。你看到结果中我想要做什么了吗?它可以像{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:4,weight:12},{name:'A',date:'2012-12-11',order:2,time:3,weight:70}@user-是的,所以你可以在
sortfcn
中做任何你想做的事。因此,类似于if($A['date==$b['date date]=$b['date]}{if($A['weight'>b['weight']){return
。请查看提供的文档链接,您就会明白我的意思。
usort($arr, "sortfcn");
function sortfcn($a, $b) {
if ($a['date'] > $b['date') { return 1; }
else if ($a['date'] < $b['date']) { return -1; }
return 0;
}