Sorting an associative array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Sorting an associative array

Post by HiddenS3crets »

I have an array like this:

Code: Select all

Array (
 [file1.php] => file
 [another.php] => file
 [dirname] => dir
 [dog.php] => file
 [anotherdir] => dir
)
What I want to do is sort the array so all the values are alphabetical, then have all the keys alphabetical too. The output would look like this:

Code: Select all

Array (
 [anotherdir] => dir
 [dirname] => dir
 [another.php] => file
 [dog.php] => file
 [file1.php] => file
)
I need to find a way to combine the usage of asort() and ksort(). Any ideas?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

[feyd@home]>php -r "$foo = array('file1.php' => 'file', 'another.php' => 'file', 'dirname' => 'dir', 'anotherdir' => 'dir'); krsort($foo); asort($foo); var_dump($foo);"
array(4) {
  ["anotherdir"]=>
  string(3) "dir"
  ["dirname"]=>
  string(3) "dir"
  ["another.php"]=>
  string(4) "file"
  ["file1.php"]=>
  string(4) "file"
}
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Post by HiddenS3crets »

feyd wrote:

Code: Select all

[feyd@home]>php -r "$foo = array('file1.php' => 'file', 'another.php' => 'file', 'dirname' => 'dir', 'anotherdir' => 'dir'); krsort($foo); asort($foo); var_dump($foo);"
array(4) {
  ["anotherdir"]=>
  string(3) "dir"
  ["dirname"]=>
  string(3) "dir"
  ["another.php"]=>
  string(4) "file"
  ["file1.php"]=>
  string(4) "file"
}
This does not work in all cases. Try it with this array:

Code: Select all

array( 'stats' => 'dir', 'filemanager' => 'dir', 'includes' => 'dir', 'index.php' => 'file', 'images' => 'dir', 'extras' => 'dir', 'bottom.php' => 'file', 'functions.js' => 'file', 'navigation.php' => 'file', 'register.php' => 'file', 'Untitled.php' => 'file' )
The output is:

Code: Select all

Array
(
    [stats] => dir
    [filemanager] => dir
    [extras] => dir
    [includes] => dir
    [images] => dir
    [bottom.php] => file
    [Untitled.php] => file
    [register.php] => file
    [navigation.php] => file
    [functions.js] => file
    [index.php] => file
)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Well, then I guess you need to figure out your own functions for it. :roll:
Post Reply