0

I would like to apply ksort in a multi-dimensional array. The goal is to sort numeric index for each level.

I tried to do a function to do this but it does not work.

function ksort_r( array &$array ){   /* ksort() for multi-dimensional array*/
    ksort( $array );
    foreach ( $array as $key=>$item ){
        if( is_array( $item ) ){
            ksort_r( $item );
        }
    }
}

example

$array = array( 
   1 => array(
        "columns" => array(
             2 => array(),
             0 => array(),
             1 => array(),
        )
   ),
   0 => array(
        "columns" => array(
             2 => array(),
             1 => array(),
             0 => array(),
        )
   )
)

output wishes :

array( 
   0 => array(
        "columns" => array(
             0 => array(),
             1 => array(),
             2 => array(),
        )
   ),
   1 => array(
        "columns" => array(
             0 => array(),
             1 => array(),
             2 => array(),
        )
   )
)
  
Nimantha
  • 6,405
  • 6
  • 28
  • 69
J.BizMai
  • 2,621
  • 3
  • 25
  • 49

1 Answers1

1

You forgot to pass the value in foreach as reference too:

foreach ( $array as $key=> &$item ) {

Or update the array index with the sorted $item:

ksort_r($item);
$array[$key] = $item;
Nimantha
  • 6,405
  • 6
  • 28
  • 69
rogeriolino
  • 1,095
  • 11
  • 21