Reputation: 68406
How can I sort a array like this by its keys, from the smaller resolution to the larger one:
$sizes = array(
'120x120' => 'large',
'60x60' => 'small',
'200x200' => 'very large',
'90x90' => 'medium',
...
?
should be:
Upvotes: 7
Views: 7322
Reputation: 12323
Try with ksort().
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
Edit: to make the answer complete, please do use the SORT_NUMERIC
flag.
Upvotes: 3
Reputation: 54425
If you take a look at PHP's Sorting Arrays manual page, you can see there are a few options for sorting the array based on its keys, of which ksort (using the SORT_NUMERIC
modifier) is most likely the one you're after.
Upvotes: 0
Reputation: 21957
$sizes = array(
'120x120' => 'large',
'60x60' => 'small',
'200x200' => 'very large',
'90x90' => 'medium');
uksort($sizes, 'userSorting');
print_r($sizes);
function userSorting($a, $b) {
$a = explode('x', $a);
$b = explode('x', $b);
return $a[0] > $b[0];
}
Upvotes: 3
Reputation: 125456
you need natural sort by keys, can use uksort
uksort($array, 'strnatcasecmp');
Upvotes: 11
Reputation: 400932
ksort()
in numeric mode should work just fine :
$sizes = array(
'120x120' => 'large',
'60x60' => 'small',
'200x200' => 'very large',
'90x90' => 'medium',
);
ksort($sizes, SORT_NUMERIC);
var_dump($sizes);
will get you :
array
'60x60' => string 'small' (length=5)
'90x90' => string 'medium' (length=6)
'120x120' => string 'large' (length=5)
'200x200' => string 'very large' (length=10)
Upvotes: 11