Home >Backend Development >PHP Tutorial >PHP development skills (2) - A case of implementing two-dimensional array sorting based on key
There are many built-in functions for processing arrays in PHP. Many times we can meet our needs and get the results we want by directly using their built-in functions; however, sometimes we cannot use The built-in functions implement our requirements, which requires us to write our own algorithms to implement our own ideas. Let's talk about how to sort a two-dimensional array according to key.
Implementation method:
<?php /** * ======================================= * Created by Zhihua_W. * Author: Zhihua_W * Date: 2016/11/26 0002 * Time: 下午 2:43 * Project: PHP开发小技巧 * Power: 实现二维数组根据key进行排序 * ======================================= */ /** * 二维数组排序 * @param array $arr 需要排序的二维数组 * @param string $keys 所根据排序的key * @param string $type 排序类型,desc、asc * @return array $new_array 排好序的结果 */ function array_sort($arr, $keys, $type = 'desc') { $key_value = $new_array = array(); foreach ($arr as $k => $v) { $key_value[$k] = $v[$keys]; } if ($type == 'asc') { asort($key_value); } else { arsort($key_value); } reset($key_value); foreach ($key_value as $k => $v) { $new_array[$k] = $arr[$k]; } return $new_array; } $arr = array( array( 'name' => 'a', 'sex' => 'm', 'sort' => 5 ), array( 'name' => 'c', 'sex' => 'm', 'sort' => 8 ), array( 'name' => 'g', 'sex' => 'm', 'sort' => 3 ), array( 'name' => 'e', 'sex' => 'w', 'sort' => 6 ), array( 'name' => 'b', 'sex' => 'w', 'sort' => 2 ), ); //打印出原数组 print_r($arr); //打印出排好序的数组 print_r(array_sort($arr,'name')); ?>
We can see from the printed results that the array is sorted according to "name".
//原数组 Array ( [0] => Array ( [name] => a [sex] => m [sort] => 5 ) [1] => Array ( [name] => c [sex] => m [sort] => 8 ) [2] => Array ( [name] => g [sex] => m [sort] => 3 ) [3] => Array ( [name] => e [sex] => w [sort] => 6 ) [4] => Array ( [name] => b [sex] => w [sort] => 2 ) ) //排序后数组 Array ( [2] => Array ( [name] => g [sex] => m [sort] => 3 ) [3] => Array ( [name] => e [sex] => w [sort] => 6 ) [1] => Array ( [name] => c [sex] => m [sort] => 8 ) [4] => Array ( [name] => b [sex] => w [sort] => 2 ) [0] => Array ( [name] => a [sex] => m [sort] => 5 ) )
The above is the detailed content of PHP development skills (2) - A case of implementing two-dimensional array sorting based on key. For more information, please follow other related articles on the PHP Chinese website!