Voting

: min(nine, nine)?
(Example: nine)

The Note You're Voting On

rick at toewsweb dot net
14 years ago
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs
= array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print
"before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print
"after:\n";
print_r($kvpairs);
?>

before:
Array
(
[noun] => thought
[animal] => fish
[abstract] => thought
[food] => fish
[verb] => fish
)
after:
Array
(
[animal] => fish
[food] => fish
[verb] => fish
[abstract] => thought
[noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.

<< Back to user notes page

To Top