If you wan't to sort JSON based data or an multidimensional object (ascending or descending), you must fetch the array/object keys for sorting - After a sort, you can build a new Object with the correct sorting.
**Example Data:**
<?php
$json = [
'nameZ' => [
'A' => true,
'F' => true,
'K' => true
],
'nameU' => 'Hello World!',
'nameA' => [
'subData' => [
'resultX' => 1,
'resultB' => 4,
'resultI' => 6
]
],
'nameK' => [
'testing' => true
],
];
?>
**Function:**
<?php
function json_sort(&$json, $ascending = true) {
$names = [];
foreach($json AS $name => $value) {
$names[] = $name;
}
if($ascending) {
asort($names);
} else {
arsort($names);
}
$result = [];
foreach($names AS $index => $name) {
if(is_array($json[$name]) || is_object($json[$name])) {
json_sort($json[$name], $ascending);
}
$result[$name] = $json[$name];
}
$json = $result;
}
?>
**Usage:**
<?php
json_sort($json, true); print_r($json);
?>
or
<?php
json_sort($json, false); print_r($json);
?>
I had written these method for generating HashValues for an API-Request. The HTTP-Request POST the JSON-Data as Body and over GET-Parameter, an digest/token will be appended to validate the JSON-Data (prevent manipulation of the JSON Data).