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){...}
Here's my error message:
Uncaught TypeError: ksort(): Argument #1 ($array) must be of type array, stdClass given
ksort works with arrays, not with objects. You need to pass true
as the second parameter to get an associative array:
$array = json_decode($json, true);
ksort($array);
echo json_encode($array);