Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: array sort by string key

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 :

  • 60x60
  • 90x90
  • 120x120
  • 200x200
  • ...
like image 915
Alex Avatar asked Apr 04 '11 06:04

Alex


People also ask

How do you sort an array by key?

The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

How can we sort an array without using sort method in PHP?

php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>

What is Rsort PHP?

The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.


2 Answers

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)


This will work because the size is a numeric -- and is found before the 'x' (not sure what will be done with the 'x' and what follows -- but, anyway, that part of the keys is useless, as it's purely redondant information)

like image 109
Pascal MARTIN Avatar answered Oct 06 '22 09:10

Pascal MARTIN


you need natural sort by keys, can use uksort

uksort($array, 'strnatcasecmp');
like image 29
Haim Evgi Avatar answered Oct 06 '22 09:10

Haim Evgi