I've the following strings as follows :
1BG200,1M400,1BA1000
And I want to to compare the above strings into Desc Order...
Code:
$sql = "SELECT * FROM collected WHERE c_no BETWEEN '".$from."' AND '".$to."' ORDER BY c_no Desc";
Output :
1M400
1BG200
1BA1000
It should be 1000 is larger, then 400, 200..How can i compare them ? I believe its not right to compare string that contains integer ! And I can't find a correct solution for my issue ?
Some people suggested using preg_match
or substr
..But as you can see there are single and double characters ex ( M and BG ).
Sorry, I'm not that familiar with PHP.. Please Help !
You can use a custom sort, looking only at the numerical part
function cmp($a, $b)
{
$numa = intval(preg_replace('/[0-9]*[A-Z]+/', '', $a));
$numb = intval(preg_replace('/[0-9]*[A-Z]+/', '', $b));
if($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
//Now get the list and sort
usort($list, "cmp");
You can use preg_replace('/[0-9][A-Z]+/', '', $var)
to remove first number and more then one letter after, and then use php usort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With