note 122896 deleted from array.sorting by cmb

From: Date: Sun, 05 Jan 2020 08:54:03 +0000
Subject: note 122896 deleted from array.sorting by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213788@lists.php.net to get a copy of this message
Note Submitter: bizarrus at icloud dot com ---- 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 = []; // Creating a named array for sorting foreach($json AS $name => $value) { $names[] = $name; } if($ascending) { asort($names); } else { arsort($names); } $result = []; foreach($names AS $index => $name) { // Sorting Sub-Data 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); // Ascending order print_r($json); ?> or <?php json_sort($json, false); // Descending order 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).

« previous php.notes (#213788) next »