du4822
2017-10-24 13:56
浏览 55
已采纳

在PHP中排序Json数据? 不同的具体数据?

This is json data in webservice, I need to sort this kind of information by top to date sort 2017..bla - 2015..bla -2014, maybe sort value "4" or title 2015 blabla.... value in a PHP script, how can I do?

"2015-09-11 09:18:11.023151": {
    "1": "4422",
    "2": "asd",
    "3": "aaa",
    "4": "2015-09-11 09:18:11.023151"
    },
"2014-10-29 13:33:14.325827": {
    "1": "5852",
    "2": "shfe",
    "3": "sds",
    "4": "2014-10-29 13:33:14.325827"
},
"2017-11-10 09:18:11.315102": {
    "1": "2323",
    "2": "sfd",
    "3": "sdf",
    "4": "2017-11-10 09:18:11.315102"
}

i try :

$example= json_decode($result, true);


usort($example, function($a, $b) {  
    return $a->{"4"} > $b->{"4"} ? -1 : 1; }); 

echo json_encode($example);

how we can do it ?

图片转代码服务由CSDN问答提供 功能建议

这是webservice中的json数据,我需要按照最新排序2017..bla对这类信息进行排序 - 2015..bla -2014,也许在PHP脚本中排序值“4”或标题2015 blabla ....值,我该怎么办?

 “2015-  09-11 09:18:11.023151“:{
”1“:”4422“,
”2“:”asd“,
”3“:”aaa“,
”4“:”2015-  09-11 09:18:11.023151“
},
”2014-10-29 13:33:14.325827“:{
”1“:”5852“,
”2“:”shfe“,\  n“3”:“sds”,
“4”:“2014-10-29 13:33:14.325827”
},
“2017-11-10 09:18:11.315102”:{
“  1“:”2323“,
”2“:”sfd“,
”3“:”sdf“,
”4“:”2017-11-10 09:18:11.315102“
} 
    
 
 

我尝试:

  $ example = json_decode($ result,true); 
 
 
usort(  $ example,function($ a,$ b){
 return $ a-> {“4”}> $ b-> {“4”}?-1:1;});  
 
echo json_encode($ example); 
   
 
 

我们如何做到这一点?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duan5801 2017-10-24 14:16
    已采纳

    Please, try this.

    $result = '{"2015-09-11 09:18:11.023151":{"1":"4422","2":"asd","3":"aaa","4":"2015-09-11 09:18:11.023151"},"2014-10-29 13:33:14.325827":{"1":"5852","2":"shfe","3":"sds","4":"2014-10-29 13:33:14.325827"},"2017-11-10 09:18:11.315102":{"1":"2323","2":"sfd","3":"sdf","4":"2017-11-10 09:18:11.315102"}}';
    
    $example= json_decode($result, true);
    usort($example, function($a, $b) { return $a["4"] > $b["4"] ? -1 : 1; }); 
    echo json_encode($example);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doureng5668 2017-10-24 14:11

    I think I fixed your problem. I started out by converting the json to an array like you did with $array = json_decode($json, true);

    next instead of using usort() i used asort().

    Asort sorts your array from high to low and works on dates (in my case)

    http://php.net/manual/en/function.asort.php

    Is this what you mean?

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题