【问题标题】:Php Group Data IdeaPHP组数据理念
【发布时间】:2013-06-10 08:55:37
【问题描述】:

如何将日期分组并计算权重总和然后放入 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},
{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}

【问题讨论】:

    标签: php arrays json sorting grouping


    【解决方案1】:

    你需要两件事,json_decode:

    $arr = json_decode($data, true);  // `true` makes an associative array
    

    还有usort

    usort($arr, "sortfcn");
    

    ...其中sortfcn 是一个字符串,其中包含用于排序的自定义函数的名称:

    function sortfcn($a, $b) {
        if ($a['date'] > $b['date') { return 1; }
        else if ($a['date'] < $b['date']) { return -1; } 
    
        return 0;
    }
    

    我还没有测试过这些,但这是主要思想,请查看文档以清除我的语法错误并更好地了解这件事。它一定会做你想做的。

    对权重求和很简单,只需foreach遍历排序后的数组并将其相加。

    【讨论】:

    • 但是如果名称和顺序相同,我们会更关心时间的重量。你看到我想要在结果中做什么了吗?
    • 它可以像 {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,时间:3,重量:70}
    • @user - 是的,所以你可以在sortfcn 中做任何你想做的事情。所以,像if ($a['date'] == $b['date']) { if ($a['weight'] &gt; $b['weight']) { return 1; } } 这样的东西。请查看提供的文档链接,您会明白我的意思。
    猜你喜欢
    • 2011-03-24
    • 2019-11-29
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2020-03-21
    相关资源
    最近更新 更多