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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1743436492, '18.116.67.230', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/web/php/snippets/array/associative/ksort(89): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78