php laravel根据月份名称按月份顺序对项目进行排序

时间:2019-09-06 06:04:13

标签: php laravel sorting collections eloquent

我有一个类似的结果集,

{"data_points":
[{
    "monthname": "Apr",
    "value": 62
},{
    "monthname": "Aug",
    "value": 1904.53
},{
    "monthname": "Feb",
    "value": 33.33
},{
    "monthname": "Jan",
    "value": 2033.33
},{
    "monthname": "Jul",
    "value": 90.83
},{
    "monthname": "Dec",
    "value": 2030
},{
    "monthname": "Mar",
    "value": 100
},{
    "monthname": "Sep",
    "value": 433.33
},{
    "monthname": "May",
    "value": 5670.93
},{
    "monthname": "Jun",
    "value": 40.4
},{
    "monthname": "Oct",
    "value": 0
},{
    "monthname": "Nov",
    "value": 31
}]}

,我想使用 data_points.monthname 使用月份顺序对项目进行排序,例如

{"data_points": [{"monthname":"Jan", "value": 2033.33}, {"monthname": "Feb", "value":33.33} ........]}

3 个答案:

答案 0 :(得分:1)

更新

为了使用Laravel提供的方法对Collection进行排序,可以使用以下代码

$collection->sort(function ($a, $b) {
            $monthA = date_parse($a['monthname']);
            $monthB = date_parse($b['monthname']);

            return $monthA["month"] - $monthB["month"];
        });

Laravel文档提到,如果您的排序很复杂,则可以使用回调Sort

如果要在Vanilla PHP中排序,则下面是代码。

$data = '{"data_points": [{ "monthname": "Apr", "value": 62 },{ "monthname": "Aug", "value": 1904.53 },{ "monthname": "Feb", "value": 33.33 },{ "monthname": "Jan", "value": 2033.33 },{ "monthname": "Jul", "value": 90.83 },{ "monthname": "Dec", "value": 2030 },{ "monthname": "Mar", "value": 100 },{ "monthname": "Sep", "value": 433.33 },{ "monthname": "May", "value": 5670.93 },{ "monthname": "Jun", "value": 40.4 },{ "monthname": "Oct", "value": 0 },{ "monthname": "Nov", "value": 31 }]}';
$decoded =  json_decode($data, true);

usort($decoded['data_points'], "compare_months");

$data = json_encode( $decoded );

print_r($data);

function compare_months($a, $b) {
    $monthA = date_parse($a['monthname']);
    $monthB = date_parse($b['monthname']);

    return $monthA["month"] - $monthB["month"];
}

基本上,您需要将月份转换为数值。然后在此基础上进行排序。

这是3v4l上的有效演示

答案 1 :(得分:1)

如果是集合,为什么不使用sortBy集合方法。

示例

$sorted = $collection->sortBy('month');

我认为它不会工作一个月,但是在那种情况下,您可以使用mapeach方法遍历集合,并另存为另一个集合或数组。

答案 2 :(得分:0)

借助答案,我得到了最佳解决方案,

$sort_collect = $result->sortBy(function ($item, $i) { 
    return ( Carbon::parse($item->monthname)->format("m") );
});
return $sort_collect;

返回所需的顺序, 谢谢@ascsoftw和Prafulla Kumar Sahu