I have an array of values that I'd like to sort alphabetically, but with numbers sorted after characters.
For instance, given the following strings:
Core 2 Duo, Core Duo, Core Quad, Core 4 Quad
I'd like it to end up ordered as so:
Core Duo, Core 2 Duo, Core Quad, Core 4 Quad
Instead, PHP's sort() function sorts it like this:
Core 2 Duo, Core 4 Quad, Core Duo, Core Quad
Natural sorting returns the same results as regular sorting.
So is there any way to tell PHP something like, "If you encounter a number, sort it as if it comes after Z"?
It seems that what you're after is a function that pushes all numeric elements of your strings to the back, e.g. "Core 2 Duo" => "Core Duo 2".
// moves numeric parts of the string to the back
function transform($s)
{
$parts = explode(' ', $s);
foreach (array_filter($parts, 'is_numeric') as $key => $value) {
unset($parts[$key]);
$parts[] = $value;
}
return join(' ', $parts);
}
// natural sort on transformed strings
function cmp($a, $b)
{
return strnatcmp(transform($a), transform($b));
}
$a = array('Core 2 Duo', 'Core Duo', 'Core Quad', 'Core 2 Quad');
usort($a, 'cmp');
print_r($a);
Here is your solution:
<?php
$array = array('Core 2 Duo', 'Core Duo', 'Core Quad', 'Core 4 Quad');
$tempArray = array();
foreach($array as $key=>$value) {
$exp = explode(" ",$value);
if(count($exp)==3) {
$tempArray[$key] = $exp[0]." ".$exp[2]." ".$exp[1];
} else {
$tempArray[$key] = $exp[0]." ".$exp[1]." "."-1";
}
}
asort($tempArray);
$sortedArray = array();
foreach($tempArray as $key=>$value) {
$sortedArray[] = $array[$key];
}
print_r($sortedArray);
?>
Output:
Array
(
[0] => Core Duo
[1] => Core 2 Duo
[2] => Core Quad
[3] => Core 4 Quad
)