Oscar Strangio
Oscar Strangio

Reputation: 149

Error while sorting decoded json: "Uncaught TypeError: ksort(): Argument #1 ($array) must be of type array, stdClass given"

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

Upvotes: 6

Views: 13362

Answers (2)

gontrollez
gontrollez

Reputation: 6548

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

Upvotes: 11

asprin
asprin

Reputation: 9833

In order to use ksort, you first have to convert the json to PHP array by using:

// The 2nd argument (true) specifies that it needs to be converted into a PHP array
$array = json_decode($your_json, true);

Then apply ksort on that array.

And finally json_encode it again to get the result back in json.

Upvotes: 3

Related Questions