欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php二维数组自定义排序

程序员文章站 2022-04-12 08:21:59
...
<?php
//对二维数组自定义排序
function array_sort($arr,$keys,$type){
    $keysvalue=array();
    $i = 0;
    foreach($arr as $key=>$val) {
        $val[$keys] = str_replace("-","",$val[$keys]);
        $val[$keys] = str_replace(" ","",$val[$keys]);
        $val[$keys] = str_replace(":","",$val[$keys]);
        $keysvalue[] =$val[$keys];
    }
    asort($keysvalue); //key值排序
    reset($keysvalue); //指针重新指向数组第一个
    foreach($keysvalue as $key=>$vals) {
        $keysort[] = $key;
    }
    $new_array = array();
    if($type != "asc"){
        for($ii=count($keysort)-1; $ii>=0; $ii--) {
            $new_array[] = $arr[$keysort[$ii]];
        }
    }else{
        for($ii=0; $ii<count($keysort); $ii++){
        $new_array[] = $arr[$keysort[$ii]];
        }
    }
    return $new_array;
}
$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',
        ),
);
echo '<pre>';
print_r(array_sort($arr,'size','asc'));
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;
        }
    }
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}
?>