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's function natcasesort() almost gets it done right EXCEPT 'Classic no Number' and 'Mega XYZ no number' won't be the first in their 'group'! I'd like to have items without any number in it to appear before their alphabetically group-items with numbers.
That's 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");
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