phparrayssorting

Sort a specified subarray by its keys


I have this array of arrays

array (size=2)
  'login' => 
    array (size=3)
      20 => 
        array (size=1)
          0 => 
            object(File)[3]
      10 => 
        array (size=1)
          0 => 
            object(Database)[4]
      5 => 
        array (size=1)
          0 => 
            object(Closure)[5]

I'm trying to reorder the position of the keys in the second level arrays (where it says 20, 10, 5) so the result should be

array (size=2)
      'login' => 
        array (size=3)
          5 => 
            array (size=1)
              0 => 
                object(File)[3]
          10 => 
            array (size=1)
              0 => 
                object(Database)[4]
          20 => 
            array (size=1)
              0 => 
                object(Closure)[5]

Solution

  • You need to do

    ksort($array['login']);
    

    This will sort the array keys so they are ascending. If you wanted them descending you would do

    krsort($array['login']);
    

    PHP has lots of handy functions for sorting arrays