Change php natcasesort to "letters only" first
I have an array
$arr=array(
"Mega XYZ no number",
"Classic no Number",
"Doppel 80x200cm",
"Classic 100x200cm",
"Mega 240x250",
"Classic 85x200cm",
"Mega 40x250",
"Profi 60x235cm",
"Mega 140x250",
);
and would like to have the following order:
Classic no Number
Classic 85x200cm
Classic 100x200cm
Doppel 80x200cm
Mega XYZ no number
Mega 40x250
Mega 140x250
Mega 240x250
Profi 60x235cm
php function natcasesort()
almost does it right. EXCEPTION ' Classic no Number
' and ' Mega XYZ no number
' will not be the first in their "group"! I would like to have elements without any number in it, so that they appear in front of their alphanumeric elements.
+3
source to share
1 answer
What is it:
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
$arr1 = str_split($a);
$arr2 = str_split($b);
$number1 = "";
$number2 = "";
for($i = 0; $i < count($arr1); $i++){
$char1 = $arr1[$i];
$char2 = $arr2[$i];
if(is_numeric($char1) && !is_numeric($char2)){
return 1;
}
if(!is_numeric($char1) && is_numeric($char2)){
return -1;
}
else if(is_numeric($char1) && is_numeric($char2)){
$number1 .= $char1;
$number2 .= $char2;
}
else {
if($char1 != $char2){
if(!empty($number1) && !empty($number2)){
$number1 = intval($number1);
$number2 = intval($number2);
return ($number1 < $number2) ? -1 : 1;
}
return ($char1 < $char2) ? -1 : 1;
}
else {
if(!empty($number1) && !empty($number2) && $number1 != $number2){
$number1 = intval($number1);
$number2 = intval($number2);
return ($number1 < $number2) ? -1 : 1;
}
}
}
}
}
usort($arr, "cmp");
+3
source to share