Obviously this is great for sorting similar filenames. Judging from the results, this natural algorithm should remove the non-numeric parts of the head and tail, and then sort the remaining numeric parts. Whether it is true or not, let's take a look at the PHP source code.
//The relevant 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 **) a);
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); 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) {
y), zend_qsort, php_array_natural_compare, 0 TSRMLS_CC) == FAILURE) {
return; &array_arg)
Sort an array using natural sort */
PHP_FUNCTION(natsort)
{
php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
Although this is the first time to view the core code of PHP, with many years of experience in reading code, it is easy to find that the core of this natural sorting algorithm is the function: strnatcmp_ex (located in the ext/standard/strnatcmp.c file).
http://www.bkjia.com/PHPjc/320396.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320396.htmlTechArticleOfficial Manual (http://us.php.net/manual/en/function.natsort.php) Copy The code is as follows: bool natsort (array nbsp;Bucket *f, *s; zval *fval, *sval; zval first, second; int...