I want to sort a single line of JSON data by the keys alphabetically using PHP. So in the end:
{"one":"morning","two":"afternoon","three":"evening","four":"night"}
becomes:
{"four":"night","one":"morning","three":"evening","two":"afternoon"}
I've tried using ksort
to no avail:
$icons = json_decode(file_get_contents("icons.json"));
ksort($icons);
foreach($icons as $icon => $code){...}
ksort works with arrays, not with strings:
$array = json_decode($json, true);
ksort($array);
echo json_encode($array);
In order to use ksort
, you first have to convert the json to PHP array by using:
// the true argument specifies that it needs to be converted into a PHP array
$array = json_encode($your_json, true);
Then apply ksort on that array.
And finally json_encode
it again to get the result back in json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With