Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort multidimensional array alphabetically

How can I sort a array like this alphabetically:

$allowed = array(
  'pre'    => array(),
  'code'   => array(),
  'a'      => array(
                'href'  => array(),
                'title' => array()
              ),
  'strong' => array(),
  'em'     => array(),
);

// sort($allowed); ?

?

like image 988
Alex Avatar asked Apr 02 '11 23:04

Alex


4 Answers

Aha! You need uksort();

Comparison of PHP sorting functions. (dam useful)

Edit: Reason is, you seem to want to sort inside arrays as well? AFAIK ksort by itself doesn't do that - it outright ignores the value of the original array.

Edit2: This ought to work (though uses recursion instead of kusort):

function ksort_deep(&$array){
    ksort($array);
    foreach($array as &$value)
        if(is_array($value))
            ksort_deep($value);
}

// example of use:
ksort_deep($allowed);

// see it in action
echo '<pre>'.print_r($allowed,true).'</pre>';

Important: As a side effect of not using uksort() if the same array references to itself, you get an infinite loop. This won't happen in normal cases, but you never know :)

like image 126
Christian Avatar answered Sep 21 '22 03:09

Christian


ksort() ?

like image 28
Amber Avatar answered Sep 21 '22 03:09

Amber


You use

ksort($allowed);

http://php.net/manual/en/function.ksort.php

like image 32
heldt Avatar answered Sep 23 '22 03:09

heldt


bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

as described here. The 'See Also' section is usually very helpful

like image 24
nietaki Avatar answered Sep 25 '22 03:09

nietaki