gpt4 book ai didi

php - 按月对 PHP JSON 数组进行排序

转载 作者:可可西里 更新时间:2023-10-31 22:40:53 25 4
gpt4 key购买 nike

我正在尝试按 MONTH 名称缩短数组。

[  
{
"order_id":34,
"user_id":17,
"sum":65000,
"month":"May"
},
{
"order_id":32,
"user_id":19,
"sum":15000,
"month":"July"
},
{
"order_id":29,
"user_id":1,
"sum":20000,
"month":"April"
}
]

有什么办法可以快速解决这个问题吗?我需要名称格式的月份。

我希望得到如下结果。

[  
{
"order_id":29,
"user_id":1,
"sum":20000,
"month":"April"
},
{
"order_id":34,
"user_id":17,
"sum":65000,
"month":"May"
},
{
"order_id":32,
"user_id":19,
"sum":15000,
"month":"July"
}
]

我试过arsortkrsortarray_reverse(),但这些方法都无法将它们短路。所以为此寻找其他解决方案。

谢谢! (提前)

最佳答案

因为你的数据是json格式,这里不能直接应用任何函数,你可以像下面这样实现:-

<?php

$data = '[
{
"order_id":34,
"user_id":17,
"sum":65000,
"month":"May"
},
{
"order_id":32,
"user_id":19,
"sum":15000,
"month":"July"
},
{
"order_id":29,
"user_id":1,
"sum":20000,
"month":"April"
}
]';

$new_array = json_decode($data,true); // convert json to php array
echo "<pre/>";print_r($new_array); // print original array

usort($new_array, "compare_months"); // using usort with callback function
var_dump($new_array); // your final sorted array

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

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

输出:- https://eval.in/598786

引用资料:-

PHP re-order array of month names

关于php - 按月对 PHP JSON 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com