【收藏】php实现二维数组排序

php关于数组操作的函数很多,然而没有一个函数能够对二维数组排序,然而在实现的项目开发过程中有时候我们需要对二维数组排序,那么下面的这段代码就能满足需求了,能很好地对二维数组排序:

<?php

/**
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2"……)
 * @author                      Chunsheng Wang <wwccss@263.net>
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by("SORT_ASC"|"SORT_DESC")
 * @param  string  $SortType1   the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
 * @return array                sorted array.
 */
function sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR") {
    if (!is_array($ArrayData)) {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for ($I = 1; $I < $ArgCount; $I++) {
        $Arg = func_get_arg($I);
        if (!eregi("SORT", $Arg)) {
            $KeyNameList[] = $Arg;
            $SortRule[] = '$' . $Arg;
        } else {
            $SortRule[] = $Arg;
        }
    }

    // Get the values according to the keys and put them to array.
    foreach ($ArrayData AS $Key => $Info) {
        foreach ($KeyNameList AS $KeyName) {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort(' . join(",", $SortRule) . ',$ArrayData);';
    eval($EvalString);
    return $ArrayData;
}

//################# 示例 #################
$arr = array(
    array(
        'name' => '学习',
        'size' => '1235',
        'type' => 'jpe',
        'time' => '1921-11-13',
        'class' => 'dd',
    ),
    array(
        'name' => '中国功夫',
        'size' => '153',
        'type' => 'jpe',
        'time' => '2005-11-13',
        'class' => 'jj',
    ),
    array(
        'name' => '编程',
        'size' => '35',
        'type' => 'gif',
        'time' => '1997-11-13',
        'class' => 'dd',
    ),
    array(
        'name' => '中国功夫',
        'size' => '65',
        'type' => 'jpe',
        'time' => '1925-02-13',
        'class' => 'yy',
    ),
    array(
        'name' => '中国功夫',
        'size' => '5',
        'type' => 'icon',
        'time' => '1967-12-13',
        'class' => 'rr',
    ),
);

print_r($arr);

//注意:按照数字方式排序时 153 比 65 小
$temp = sysSortArray($arr, "name", "SORT_ASC", "type", "SORT_DESC", "size", "SORT_ASC", "SORT_STRING");

print_r($temp);
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值