Home  >  Article  >  Backend Development  >  Several PHP ways to sort two-dimensional arrays

Several PHP ways to sort two-dimensional arrays

小云云
小云云Original
2018-03-16 15:29:252725browse

This article mainly shares with you several ways to sort two-dimensional arrays in PHP. There are two methods in total. I hope it can help you.

Method one

function multiSort($arr, $field, $sort = SORT_ASC){
    array_multisort(array_column($arr, $field), SORT_ASC, $arr);    return $arr;
}

Method two:

function multiSort($arr, $field, $sort = SORT_ASC){
    $columns = array_column($arr, $field);    // 取出一列数据

    // 进行保持索引关系的排序
    if($sort != SORT_ASC){
        arsort($columns);
    }else{
        asort($columns);
    }    $result = [];    // 按照排序好的顺序从原数组中获取数据
    foreach ($columns as $key => $value) {        $result[] = $arr[$key];
    }    return $result;
}

Related recommendations:

Two ways to merge two-dimensional arrays in PHP

javascript two-dimensional array interview questions

php implements two-dimensional array quick sorting algorithm Example

The above is the detailed content of Several PHP ways to sort two-dimensional arrays. 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