Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Sort JSON data by keys

Tags:

json

php

sorting

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){...}
like image 786
Oscar Strangio Avatar asked Dec 14 '22 22:12

Oscar Strangio


2 Answers

ksort works with arrays, not with strings:

$array = json_decode($json, true);
ksort($array);
echo json_encode($array);  
like image 134
gontrollez Avatar answered Dec 30 '22 14:12

gontrollez


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.

like image 30
asprin Avatar answered Dec 30 '22 15:12

asprin