Keys in PHP array are not sorted numerically

I have a PHP array with keys that contain the number year and week, for example:

year-week 

Using the built-in ksort function, it returns them like this:

 ksort($array); 2011-21 2011-3 2011-44 2011-45 

Is it possible that they are sorted in numbers like this:

 2011-3 2011-21 2011-44 2011-45 
+4
source share
6 answers

You will get the result you want if you format them with a two-digit week. Something more like 2011-03. See Sprint_f ().

+1
source

Use uksort to sort keys and use strnatcmp .

 uksort($array, function($a,$b){ return strnatcmp($a,$b); }); 
+8
source

If you use PHP> = 5.4, use ksort($array, SORT_NATURAL);

+7
source

You can use natsort

 $a = array_keys($myarray); // $a now has // array('2011-21', '2011-3', '2011-45', '2011-44'); natsort($a); 

Will print

 2011-3 2011-21 2011-44 2011-45 

Then you can use the $a array as a reference to each element of the array that stores the data (in the example above $myarray )

+2
source

You can use ksort with the natural flag. (Only supported PHP 5.4+)

 ksort($array, SORT_NATURAL); 
+1
source

I see much simpler solutions, but here was my initial thought:

 function cmp($a, $b) { $comp1 = explode('-', $a); $comp2 = explode('-', $b); $year1 = (int) $comp1[0]; $year2 = (int) $comp2[0]; $week1 = (int) $comp1[1]; $week2 = (int) $comp2[1]; if ($year1 == $year2 && $week1 == $week2) { return 0; } elseif ($year1 == $year2) { return ($week1 < $week2) ? -1 : 1; } else { return ($year1 < $year2) ? -1 : 1; } } $array = array('2011-21', '2011-3', '2011-44', '2011-45'); uasort($array, 'cmp'); 
0
source

Source: https://habr.com/ru/post/1439230/


All Articles