I'm trying to sort an array by its numeric keys as if they were not numbers -- I don't want natural sorting.
$arr = [
'1000' => 'DUMMY',
'1001' => 'TEST',
'100001' => 'DUMMY1',
'100002' => 'DUMMY3',
'100004' => 'DUMMY4',
'100100' => 'test1',
'100102' => 'DUMMY123'
];
After sorting, the result should be:
[
'1000' => 'DUMMY',
'100001' => 'DUMMY1',
'100002' => 'DUMMY3',
'100004' => 'DUMMY4',
'1001' => 'TEST',
'100100' => 'test1',
'100102' => 'DUMMY开发者_运维百科123'
]
Because your array keys are "big-endian", you can explicitly sort the keys as strings (overriding the default behavior of `sort() to sort numeric values numerically). (Demo)
ksort($arr, SORT_STRING);
I'm not really sure understand what you want.
But i guess it's something like that:
this sort the array
1st : by the first 4 digits of the key
2nd : by the last 2 digits if they're present
$arr = array(
'100102' => 'DUMMY123',
'100100' => 'test1',
'1000' => 'DUMMY',
'100004' => 'DUMMY4',
'100001' => 'DUMMY1',
'100002' => 'DUMMY3',
'1001' => 'TEST',
);
function mysort($a, $b) {
preg_match('/^(\d{4})(\d\d)?$/', $a, $ma);
preg_match('/^(\d{4})(\d\d)?$/', $b, $mb);
if ($ma[1] == $mb[1]) {
if (!isset($ma[2])) $ma[2] = '';
if (!isset($mb[2])) $mb[2] = '';
return strcmp($ma[2], $mb[2]);
}
return strcmp($ma[1], $mb[1]);
}
uksort($arr, 'mysort');
print_r($arr);
Output:
Array
(
[1000] => DUMMY
[100001] => DUMMY1
[100002] => DUMMY3
[100004] => DUMMY4
[1001] => TEST
[100100] => test1
[100102] => DUMMY123
)
asort() should do the trick no matter how many extra 2-character subcategories you add. With the SORT_STRING flag the category doesn't even have to be a string.
$arr =('100001'=>'DUMMY1',
'1000'=>'DUMMY',
'1001'=>'TEST',
'100002'=>'DUMMY3',
'100004'=>'DUMMY4',
'100102'=>'DUMMY123',
'100100'=>'test1');
asort($arr, SORT_STRING);
Should result in
$arr =('1000'=>'DUMMY',
'100001'=>'DUMMY1',
'100002'=>'DUMMY3',
'100004'=>'DUMMY4',
'1001'=>'TEST',
'100100'=>'test1',
'100102'=>'DUMMY123');
精彩评论