PHP sorts largest to lowest for chart

I am creating a CSS diagram that lists items from the highest to the lowest depending on the value of a number. The problem is that "rsort" seems to only take into account the first 5 digits (or, as it seems). This causes it to show items above 100,000 below other numbers. An 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, element 1 is actually a lower number, but it is rated higher because any element over 100,000 receives lower treatment. Is there any way around this?

+4
source share
2 answers

I believe you should use natsort () . This happens when you try to sort numbers that are processed as a string. Here is an example:

 $a=array('1a','2a','3a','10a','15a'); rsort($a); echo implode(',',$a); // outputs 3a,2a,1a,15a,10a 

But you expect the output as follows:

 15a,10a,3a,2a,1a 

To do this, 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 
+4
source

Since the $ item_rank array has string values, rsort sorts it in alphabetical order. In alphabetical order, "2" will appear before "10", although 10> 2.

You need to implement natsort for this type of sorting. Verification - http://us3.php.net/manual/en/function.natsort.php

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 ) 
+1
source

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


All Articles