up vote 3 down vote favorite
share [fb]

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); ?

?

link|improve this question

possible duplicate of Order multidimensional array recursively at each level in PHP – zaf Jul 20 '11 at 14:00
feedback

4 Answers

up vote 4 down vote accepted

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 :)

link|improve this answer
That does not work. You're missing bits in the foreach loop. – zaf Jul 20 '11 at 14:00
What parts? I'm not using keys, I'm just sorting the value. – Christian Sciberras Jul 20 '11 at 14:43
1  
firstly, what does 'is_array()' do? – zaf Jul 20 '11 at 14:48
Ah, right. Fixed. Missed passing the parameter. – Christian Sciberras Jul 21 '11 at 10:00
feedback

ksort() ?

link|improve this answer
feedback

You use

ksort($allowed);

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

link|improve this answer
feedback
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.