博主在項目開發中,發現了這兩個需求,而後整理了這兩個方法與你們分享。歡迎吐槽,歡迎轉載使用。話很少說,先上代碼:數組
/** * 二維數組按照指定鍵值去重 * @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; }
再來看兩個示例:spa
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 }
明白了沒,哈哈,是否是很實用。。指針