Page 1 of 1
Sorting an associative array
Posted: Mon Aug 21, 2006 12:07 pm
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?
Posted: Mon Aug 21, 2006 12:17 pm
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"
}
Posted: Mon Aug 21, 2006 12:33 pm
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
)
Posted: Mon Aug 21, 2006 12:41 pm
by feyd
Well, then I guess you need to figure out your own functions for it.
