Change order of JSON in PHP without key/value pair
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)?
Answer
Solution:
Just sort the data before encoding it, with something like ksort:
That way, the array that
$ret
seems to return will be sorted by key (the date) and then be encoded in that sorted order.Answer
Solution:
Answer
Solution:
You can use ksort, which can sort your array by key.
You can use sort flags as well, which are well-described here.