我知道这个问题并不新鲜,但我没有找到解决方案。我有一个返回 JSON 的 API 请求:$values = '{"retcode" : "0 Done", "trans_id" : "326678", "answer" : [ { "City" : "New York", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "0.66480", "Average" : "0.66485", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0" } , { "City" : "Berlin","Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "0.89917", "Average" : "0.89920", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0" } , { "City" : "Paris", "Digits" : "3", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "119.680", "Average" : "119.684", "Last" : "0.000", "Volume" : "0", "VolumeReal" : "0" } , { "City" : "Athens", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "1.11211", "Average" : "1.11213", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0" } , { "City" : "Beijing", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "1.23677", "Average" : "1.23686", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0" 我将 JSON 转换为一个数组,并创建一个自定义顺序取决于城市的数组此代码返回与 json_decode 之后相同的数组。有什么建议么?提前致谢。
1 回答
ITMISS
TA贡献1871条经验 获得超8个赞
只需在 usort 函数中将数组 $values 更改为 $values['answer']
$values=json_decode($values, true);
$order = array('Rome', 'Berlin', 'Tokyo','Beijing',
'New York','Athens','Moscow','Los Angeles',
'Paris','Madrid','Chicago','Melbourne','Amman');
usort($values['answer'], function ($a, $b) use ($order) {
$pos_a = array_search($a['City'], $order);
$pos_b = array_search($b['City'], $order);
return $pos_a - $pos_b;
});
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消