PHP 二维数组按照指定键值去重、排序
博主在项目开发中,发现了这两个需求,然后整理了这两个方法与大家分享。欢迎吐槽,欢迎转载使用。话不多说,先上代码:
/** * 二维数组按照指定键值去重 * @param $arr 需要去重的二维数组 * @param $key 需要去重所根据的索引 * @return mixed */ function arr_uniq($arr,$key) { $key_arr = []; foreach ($arr as $k => $v) { if (in_array($v[$key],$key_arr)) { unset($arr[$k]); } else { $key_arr[] = $v[$key]; } } sort($arr); return $arr; } /** * 二维数组按指定的键值排序 * @param $array 需要排序的二维数组 * @param $keys 需要排序根据的索引 * @param string $type 正序/倒叙(默认倒序) * @return array|string */ function array_sort( $array, $keys, $type='asc' ) { if( !isset( $array ) || !is_array( $array ) || empty( $array ) ) return ''; if( !isset( $keys ) || trim( $keys ) == '' ) return ''; if( !isset( $type ) || $type == '' || !in_array( strtolower( $type ), array( 'asc', 'desc' ) ) ) return ''; $keysvalue = []; foreach( $array as $key => $val ) { $val[ $keys ] = str_replace( '-', '', $val[ $keys ] ); $val[ $keys ] = str_replace( ' ', '', $val[ $keys ] ); $val[ $keys ] = str_replace( ':', '', $val[ $keys ] ); $keysvalue[] = $val[ $keys ]; } asort( $keysvalue ); //key值排序 reset( $keysvalue ); //指针重新指向数组第一个 foreach( $keysvalue as $key => $vals ) $keysort[] = $key; $keysvalue = []; $count = count( $keysort ); if( strtolower( $type ) != 'asc' ) { for( $i = $count - 1; $i >= 0; $i-- ) $keysvalue[] = $array[ $keysort[ $i ] ]; }else{ for( $i = 0; $i < $count; $i++ ) $keysvalue[] = $array[ $keysort[ $i ] ]; } return $keysvalue; }
再来看两个示例:
1 2 $arr = [ 3 [ 4 'total'=>123, 5 'serve'=>456, 6 'speed'=>789 7 ], 8 [ 9 'total'=>123, 10 'serve'=>45, 11 'speed'=>89 12 ], 13 [ 14 'total'=>1234, 15 'serve'=>456, 16 'speed'=>789 17 ], 18 [ 19 'total'=>"123", 20 'serve'=>456, 21 'speed'=>789 22 ] 23 ];
// 去重 24 $re = arr_uniq($arr,'total'); 25 var_dump($re); 26 输出: 27 array(2) { 28 [0] => 29 array(3) { 30 'total' => 31 int(123) 32 'serve' => 33 int(456) 34 'speed' => 35 int(789) 36 } 37 [1] => 38 array(3) { 39 'total' => 40 int(1234) 41 'serve' => 42 int(456) 43 'speed' => 44 int(789) 45 } 46 } 47
//排序 48 $re = array_sort($arr, 'speed', 'desc'); 49 var_dump($re); 50 51 输出: 52 array(4) { 53 [0] => 54 array(3) { 55 'total' => 56 string(3) "123" 57 'serve' => 58 int(456) 59 'speed' => 60 int(789) 61 } 62 [1] => 63 array(3) { 64 'total' => 65 int(1234) 66 'serve' => 67 int(456) 68 'speed' => 69 int(789) 70 } 71 [2] => 72 array(3) { 73 'total' => 74 int(123) 75 'serve' => 76 int(456) 77 'speed' => 78 int(789) 79 } 80 [3] => 81 array(3) { 82 'total' => 83 int(123) 84 'serve' => 85 int(45) 86 'speed' => 87 int(89) 88 } 89 }
明白了没,哈哈,是不是很实用。。