-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

2
  • No: pastebin.com/PzMgxWNV Commented Nov 28, 2020 at 17:06
  • You need to do it before casting your array into an object. Commented Nov 28, 2020 at 18:39

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Did I try it wrong? pastebin.com/0jGDeNA9 (tested in terminal)
you had to cast $obj in the second var_dump here is the right version : <?php function array_ksort(array $array) { ksort($array); return $array; } $obj=(object)array("this"=>"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); ?>
Thanks, that looks to work; though I rewrote the code in JS already and still had to sort it...
Correction seems to not sort 100% properly with real data at least in layer 3, this was how i did it: pastebin.com/gVqQeQbx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.