Home >Backend Development >PHP Tutorial >PHP two-dimensional array sorting—default natural sorting

PHP two-dimensional array sorting—default natural sorting

小云云
小云云Original
2017-11-15 15:46:131735browse

What is a two-dimensional array? A two-dimensional array is essentially an array with arrays as array elements, that is, "array of arrays", type specifier array name [constant expression] [constant expression]. A two-dimensional array is also called a matrix, and a matrix with the same number of rows and columns is called a variable square matrix. Symmetric matrix a[i][j] = a[j][i], diagonal matrix: There are zero elements outside the main diagonal of an n-order square matrix. PHP two-dimensional array sorting function, default natural sorting, that is, sort sorting. Here you can specify multiple methods to sort by a certain value in the two-dimensional array. See the program comments below for details.

/**
 * @function 二维数组自然排序
 * @author www.phpernote.com
 * @param array $array 需要排序的数组(二维)
 * @param string key 需要根据哪个键排序
 * @param string order 排序方式(SORT_ASC,SORT_DESC)
 * @param string type 排序方法(SORT_REGULAR,SORT_NUMERIC,SORT_STRING)
 * @return array sorted array.
 */
function phpSortArray($array,$key,$order="SORT_ASC",$type="SORT_REGULAR"){
    if(!is_array($array)||empty($$array)){
        return $array;
    }
    $ArgCount=func_num_args();//返回传递到目前定义函数的参数数目
    for($I=1;$I<$ArgCount;$I++){
        $Arg=func_get_arg($I);
        if(!eregi("SORT",$Arg)){
            $KeyNameList[]=$Arg;
            $SortRule[]=&#39;$&#39;.$Arg;
        }else{
            $SortRule[]=$Arg;
        }
    }
    foreach($array AS $Key=>$Info){
        foreach($KeyNameList as $KeyName){
            ${$KeyName}[$Key]=$Info[$KeyName];
        }
    }
    $EvalString=&#39;array_multisort(&#39;.join(",",$SortRule).&#39;,$array);&#39;;
    eval($EvalString);
    return $array;
}

The above is a tutorial on the default natural sorting of PHP two-dimensional array sorting. I hope it will be helpful to everyone.

Related recommendations:

PHP two-dimensional array assignment and traversal function implementation example

What is a PHP two-dimensional array? PHP II Detailed explanation of dimensional array examples

A PHP two-dimensional array sorting function sharing

The above is the detailed content of PHP two-dimensional array sorting—default natural sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn