I'm creating a CSS chart that lists items from highest to lowest based on the number value. The problem is "rsort" seems to only count the first 5 digits (or so it seems). This is resulting in it showing items higher than 100,000 below the other numbers. Example of this problem is below:
$ITEM_1 = "95000";
$ITEM_2 = "103000";
..
$item_rank[]= "<li>$ITEM_1 Item 1</li>";
$item_rank[]= "<li>$ITEM_2 Item 2</li>";
..
rsort($item_rank); // sort highest numbers to lowest
echo "<ul>";
echo $item_rank[0];
echo $item_rank[1];
..
echo "</ul>";
In this case, Item 1 is actually a lower number, but it is being ranked higher because any item over 100,000 gets treated lower. Is there a way around this?
I believe you should be using natsort() . This happens when you try to sort numbers treated as string. Here's an example:
$a=array('1a','2a','3a','10a','15a');
rsort($a);
echo implode(',',$a); // outputs 3a,2a,1a,15a,10a
But you are expecting an output like this:
15a,10a,3a,2a,1a
To do that, use natsort and array_reverse() :
$a=array('1a','2a','3a','10a','15a');
natsort($a);
$a=array_reverse($a);
echo implode(',',$a); // outputs 15a,10a,3a,2a,1a
Since the $item_rank array has string values, rsort will sort it in alphabetic order. In alphabetic order reverse sort, "2" will come before "10" even though 10 > 2.
You need to implement natsort for this type of sorting. Check - http://us3.php.net/manual/en/function.natsort.php
The example from php.net:
<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");
asort($array1);
echo "Standard sorting\n";
print_r($array1);
natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>
Standard sorting
Array
(
[3] => img1.png
[1] => img10.png
[0] => img12.png
[2] => img2.png
)
Natural order sorting
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.