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


Change order of JSON in PHP without key/value pair

我有一种情况,需要按日期对JSON对象进行排序。我在网上搜索过解决方案,所有的东西都指向PHP的usort函数,但所有的例子都有一个键/值对可以排序

这就是我加载提要的方式:

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

Wich导致以下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,
      [..]
   }
}

正如你所看到的,数据没有按日期正确排序,但日期值是关键,所以我如何按日期对对象进行排序(2015-12-10、2015-12-11、2015-12-12、2015-12-13、2015-12-14、2015-12-15)?

只需在编码前对数据进行排序,使用类似ksort:的方法

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

这样,$ret似乎返回的数组将按关键字(日期)排序,然后按排序顺序进行编码。

$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);

您可以使用ksort,它可以按键对数组进行排序。

您也可以使用排序标志,这里对此进行了很好的描述。