How to use PHP to sort a two-dimensional array by key value

little bottle
Release: 2023-04-06 09:36:02
forward
3621 people have browsed it

This article is about using PHP to implement a method of sorting two-dimensional arrays by key value. It has certain reference value. Friends who are interested must learn about it.

During the development process, we often need to sort the two-dimensional array according to a certain key of the array. Here are two encapsulated methods, which can be placed in the public function module and called directly when needed later. Can.

/**
 * 二维数组按照键值降序排序
 * @param array $arr   待排序数组
 * @param string $key  键值
 * @return mixed
 */
function sortByKeyDesc($arr, $key) {

    array_multisort(array_column($arr, $key), SORT_DESC, $arr);
    return $arr;

}

/**
 * 二维数组按照键值升序排序
 * @param array $arr   待排序数组
 * @param string $key  键值
 * @return mixed
 */
function sortByKeyAsc($arr, $key) {

    array_multisort(array_column($arr, $key), SORT_ASC, $arr);
    return $arr;

}
$arr = [
    ['name' => 'itbsl', 'priority' => 23],
    ['name' => 'jack', 'priority' => 3],
    ['name' => 'rose', 'priority' => 12],
    ['name' => 'pick', 'priority' => 45],
    ['name' => 'binbin', 'priority' => 68],
    ['name' => 'didi', 'priority' => 56789],
    ['name' => 'mobike', 'priority' => 0],
];

//把数组arr按照priority的值降序(从大到小)排序
$result = sortByKeyDesc($arr, 'priority');
Copy after login

Related tutorials: PHP video tutorial

The above is the detailed content of How to use PHP to sort a two-dimensional array by key value. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template