当前位置:首页 > PHP教程 > PHP高级教程

php natsort内核函数浅析第1/2页

官方手册(http://us.php.net/manual/en/function.natsort.php)

复制代码 代码如下:

bool natsort ( array &$array )
this function implements a sort algorithm that orders alphanumeric strings in the way a human being would 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.

据官方手册还可以得到这样的结果:

img1.png img2.png img10.png img12.png

显然这很适合对类似文件名的排序。从结果看这种自然算法应该是去掉头和尾的非数字部分,然后对留下来的数字部分进行排序,究竟是不是,还是看一下php源码吧。
复制代码 代码如下:

//从ext/standard/array.c抽取的相关代码如下
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);
        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);
}
/* }}} */

虽然是第一次查看php的内核代码,不过凭借多年看代码的经验,还是很容易找到这个自然排序算法的核心就是函数:strnatcmp_ex(位于ext/standard/strnatcmp.c文件中)。
12下一页阅读全文


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!