Search notes:

PHP: ksort

ksort($ary) sort an associative by the value of its keys.
<?php

$jsonTxt = '{
  "num":  42,
  "txt": "Hello world",
  "ary": [1,2,3,4],
  "obj": {}
}';

#
#  Use true for second parameter so
#  that json_decode returns an
#  associative array (aka dictionary):
#
$json = json_decode($jsonTxt, true);

#
#  The keys (or the dictionary) is
#  sorted in place!
#
ksort($json);

#
#  Iterate over each key.
#
foreach(array_keys($json) as $key) {
   print("$key\n");
}

?>
Github repository about-php, path: /array/associative/ksort.php
ksort() does not have a noticable effect on an ordinary array:
<?php

  $foo = [3,1,4,2];

  ksort($foo);

  foreach($foo as $f) { print("$f\n");}

?>
Github repository about-php, path: /array/associative/ksort-array.php

See also

krsort() sorts an array by key in descending order.
sort()
Arrays

Index