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');
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!