Last active
August 29, 2015 14:20
-
-
Save lsloan/b4800602152ba861235b to your computer and use it in GitHub Desktop.
My attempt to recursively sort data in nested arrays and objects. This is helpful for sorting data in JSON by key.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JsonSortTest extends PHPUnit_Framework_TestCase { | |
public $fixtureFilename = 'fixture.json'; | |
public $outputFilename = 'output.json'; | |
public $fixtureJson; | |
function ksortObjectsRecursive(&$data, $sortFlags = SORT_REGULAR) { | |
if (!function_exists('ksortObjectsRecursiveCallback')) { | |
function ksortObjectsRecursiveCallback(&$data, $unusedKey, $sortFlags) { | |
$dataWasCastAsArray = false; | |
if (is_object($data)) { | |
$data = (array)$data; | |
$dataWasCastAsArray = true; | |
} | |
$success = is_array($data) && | |
ksort($data, $sortFlags) && | |
array_walk($data, __FUNCTION__, $sortFlags); | |
if ($dataWasCastAsArray) { | |
$object = new stdClass(); | |
foreach ($data as $key => $value) { | |
$object->$key = $value; | |
} | |
$data = $object; | |
} | |
return $success; | |
} | |
} | |
return ksortObjectsRecursiveCallback($data, null, $sortFlags); | |
} | |
function testJsonSorting() { | |
$this->fixtureJson = file_get_contents($this->fixtureFilename); | |
$jsonObjects = json_decode($this->fixtureJson); | |
$this->ksortObjectsRecursive($jsonObjects); | |
$jsonString = json_encode($jsonObjects, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); | |
file_put_contents($this->outputFilename, $jsonString); | |
$this->assertJsonStringEqualsJsonFile($this->fixtureFilename, $jsonString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Admittedly, this has some limitations. When an object of any type is passed to the method, it will be returned as StdClass, rather than its original type. Also, this may run into access problems when trying to read or write certain object properties.