Official Manual (http://us.php.net/manual/en/function.natsort.php)
CopyCode The Code is as follows: bool natsort (array & $ array)
This function implements a sort algorithm that orders alphanumeric strings in the way a human being wocould while maintaining key/value associations. this is described as a "natural ordering ". an example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort () can be seen in the example below.
According to the official manual, the following results can be obtained:
Img1.png img2.png img10.png img12.png
Obviously, this is suitable for sorting similar file names. From the results, we can see that this is natural. Algorithm It should be to turn around and the end of the non-numeric part, and then sort the remaining numeric part, whether it is, let's take a look at the PHP source code.Copy code The Code is as follows: // The Code extracted from ext/standard/array. C is as follows:
Static int php_array_natural_general_compare (const void * a, const void * B, int fold_case )/*{{{*/
{
Bucket * F, * s;
Zval * fval, * sval;
Zval first, second;
Int result;
F = * (bucket **) );
S = * (bucket **) B );
Fval = * (zval **) F-> pdata );
Sval = * (zval **) S-> pdata );
First = * fval;
Second = * sval;
If (z_type_p (fval )! = Is_string ){
Zval_copy_ctor (& First );
Convert_to_string (& First );
}
If (z_type_p (sval )! = Is_string ){
Zval_copy_ctor (& second );
Convert_to_string (& second );
}
Result = strnatcmp_ex (z_strval (first), z_strlen (first), z_strval (second), z_strlen (second), fold_case );
If (z_type_p (fval )! = Is_string ){
Zval_dtor (& First );
}
If (z_type_p (sval )! = Is_string ){
Zval_dtor (& second );
}
Return result;
}
/*}}}*/
Static int php_array_natural_compare (const void * a, const void * B tsrmls_dc )/*{{{*/
{
Return php_array_natural_general_compare (a, B, 0 );
}
/*}}}*/
Static void php_natsort (internal_function_parameters, int fold_case )/*{{{*/
{
Zval * array;
If (zend_parse_parameters (zend_num_args () tsrmls_cc, "A", & array) = failure ){
Return;
}
If (fold_case ){
If (zend_hash_sort (z_arrval_p (array), zend_qsort, php_array_natural_case_compare, 0 tsrmls_cc) = failure ){
Return;
}
} Else {
If (zend_hash_sort (z_arrval_p (array), zend_qsort, php_array_natural_compare, 0 tsrmls_cc) = failure ){
Return;
}
}
Return_true;
}
/*}}}*/
/* {Proto void natsort (array & array_arg)
Sort an array using natural sort */
Php_function (natsort)
{
Php_natsort (internal_function_param_passthru, 0 );
}
/*}}}*/
Although it was the first time to view the PHP kernel code, with years of experience in code reading, it is easy to find that the core of this natural sorting algorithm is the function: strnatcmp_ex (located in ext/standard/strnatcmp. c file ).