For example, the following array:
array(
'0' => 'z1',
'1' => 'Z10',
'2' => 'z12',
'3' => 'Z2',
'4' => 'z3',
)
After sorting, should become:
array(
'0' => 'z1',
'3' => 'Z2',
'4' => 'z3',
'1' => 'Z10',
'2' => 'z12',
)
The trick to solving this problem is to use three special flags with the standard asort() library function:
asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)
The function asort() is a variant of the standard function sort() that preserves the index association. The three flags used above SORT_STRING, SORT_FLAG_CASE and SORT_NATURAL forces the sort function to treat the items as strings, sort in a case-insensitive way and maintain natural order respectively.
Note: Using the natcasesort() function would not be a correct answer, since it would not maintain the original index association of the elements of the array.
No comments:
Post a Comment