时间:2021-07-01 10:21:17 帮助过:36人阅读
实现方法:
<?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')); ?>
通过打印出的结果我们就可以看到,数组根据“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 ) )
以上就是PHP开发技巧(二)-实现二维数组根据key进行排序的案例的详细内容,更多请关注Gxl网其它相关文章!