Reputation: 169
This is my code:
$array = [
'd 01 x'=>'b',
'd 3 x'=>'a',
'd 02 x'=>'b',
'd 9 x'=>'b',
'd 8 x'=>'b',
'd 07 x'=>'b',
'd 10 x'=>'b'
];
ksort($array);
print_r($array);
And this is result:
Array ( [d 01 x] => b [d 02 x] => b [d 07 x] => b [d 10 x] => b [d 3 x] => a [d 8 x] => b [d 9 x] => b )
Why after d 02 x
not showing d 3 x
?
How I can fix it?
Thank you
Upvotes: 0
Views: 220
Reputation: 807
You most likely want to use uksort for this. uksort allows you to supply your own function which it will use for sorting.
The following piece of code first defines a function to transform the string key into it's integer representation, and compares the two supplied items by using the space ship operator.
function toInt($element)
{
return (int)str_replace(['d', ' ', 'x'], '', $element);
}
uksort($array, function ($first, $second) {
$f = toInt($first);
$s = toInt($second);
return $f <=> $s;
});
print_r($array);
output:
Array
(
[d 01 x] => b
[d 02 x] => b
[d 3 x] => a
[d 07 x] => b
[d 8 x] => b
[d 9 x] => b
[d 10 x] => b
)
Upvotes: 2