-1

So lets say I have this:

<?php
    $obj=(object)array("this"=>"that","and"=>"the","other"=>(object)array("layers"=>"make","things"=>"more","fun"=>(object)array("every"=>"time","foo"=>"bar")));
    var_dump($obj);
?>

which outputs this:

object(stdClass)#3 (3) {
  ["this"]=>
  string(4) "that"
  ["and"]=>
  string(3) "the"
  ["other"]=>
  object(stdClass)#2 (3) {
    ["layers"]=>
    string(4) "make"
    ["things"]=>
    string(4) "more"
    ["fun"]=>
    object(stdClass)#1 (2) {
      ["every"]=>
      string(4) "time"
      ["foo"]=>
      string(3) "bar"
    }
  }
}

But I want it sorted by keys like this preferably without having to make a array or ever layer of keys and sort it and rebuilding the object in order like this:

object(stdClass)#3 (3) {
  ["and"]=>
  string(4) "the"
  ["other"]=>
  object(stdClass)#2 (3) {
    ["fun"]=>
    object(stdClass)#1 (2) {
      ["every"]=>
      string(4) "time"
      ["foo"]=>
      string(3) "bar"
    }
    ["layers"]=>
    string(4) "make"
    ["things"]=>
    string(4) "more"
  }
  ["this"]=>
  string(3) "that"
}

I think web browsers will do this sorting automatically as I seem to recall having to workaround this when I had a custom sorting feature I made break some years ago in firfox, so I could just json_encode it and let the client handle this part so the browser will just sort it with no sorting effort on my part

1 Answers1

0
// Just sort and return the sorted array
function array_ksort(array $array) {
    ksort($array);
    return $array;
}

$obj = (object) array_ksort(array_map(function($value) { return !is_object($value) ? $value : (object) array_ksort((array) $value);}, $obj));

Check result here : https://3v4l.org/2hZsB

ybenhssaien
  • 3,427
  • 1
  • 10
  • 12
  • Did I try it wrong? https://pastebin.com/0jGDeNA9 (tested in terminal) – GM-Script-Writer-62850 Nov 28 '20 at 16:49
  • you had to cast `$obj` in the second `var_dump` here is the right version : `"that","and"=>"the","other"=>(object)array("layers"=>"make","things"=>"more","fun"=>(object)array("every"=>"time","foo"=>"bar"))); var_dump($obj); $obj = (object) array_ksort(array_map(function($value) { return !is_object($value) ? $value : (object) array_ksort((array) $value);}, (array) $obj)); var_dump($obj); ?>` – ybenhssaien Nov 29 '20 at 21:49
  • Thanks, that looks to work; though I rewrote the code in JS already and still had to sort it... – GM-Script-Writer-62850 Nov 30 '20 at 02:46
  • Correction seems to not sort 100% properly with real data at least in layer 3, this was how i did it: https://pastebin.com/gVqQeQbx – GM-Script-Writer-62850 Nov 30 '20 at 02:59