dream198731 2015-12-10 09:10
浏览 85
已采纳

在没有键/值对的情况下在PHP中更改JSON的顺序

I have a situation where i need to sort a JSON object by date. I've searched for solutions online and everything points in the direction of PHP's usort function, but all examples have a key/value pair to sort on.

This is how i load the feed:

$ret = file_get_contents($url);
$res = json_encode($ret);

Wich results in the following JSON

{  
   "2015-12-14":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
  },
   "2015-12-15":{  
      "direction":"S",
      "snowfall":3.0,
      [..]
   },
   "2015-12-12":{  
      "direction":"SE",
      "snowfall":0.0,
      [..]
   },
   "2015-12-13":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   },
   "2015-12-10":{  
      "direction":"E",
      "snowfall":0.0,
      [..]
   },
   "2015-12-11":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   }
}

As you can see, the data is not properly ordered by date, but the date value is the key so how can i sort the object by date (2015-12-10, 2015-12-11, 2015-12-12, 2015-12-13, 2015-12-14, 2015-12-15)?

  • 写回答

3条回答 默认 最新

  • duandan5471 2015-12-10 09:19
    关注
    $json = '{  
       "2015-12-14":{  
    
          "direction":"S",
    
          "snowfall":0.0
    
      },
    
       "2015-12-15":{  
    
          "direction":"S",
    
          "snowfall":3.0
    
       },
    
       "2015-12-12":{  
    
          "direction":"SE",
    
          "snowfall":0.0
    
       },
    
       "2015-12-13":{  
    
          "direction":"S",
    
          "snowfall":0.0
    
       },
    
       "2015-12-10":{  
    
          "direction":"E",
    
          "snowfall":0.0
    
       },
    
       "2015-12-11":{  
    
          "direction":"S",
    
          "snowfall":0.0
    
       }
    
    }';
    
    $array = get_object_vars(json_decode($json));
    
    ksort($array);
    
    echo json_encode((object)$array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?