function getSortArray($data,$key,$sort='ASC') { if(!is_array($data)) { return false; } $len = count($data); for($k=1; $k { for($j=$len-1,$i=0;$i { if(strtoupper($sort) == 'DESC') { $flag = $data[$j][$key]>$data[$j-1][$key]; } else { $flag = $data[$j][$key] } if($flag) { $tmp = $data[$j]; $data[$j] = $data[$j-1]; $data[$j-1] = $tmp; } } } return $data; } 使用方法: $a = array( array('name'=>'stone','age'=>17,'sex'=>'男'), array('name'=>'sunny','age'=>28), array('name'=>'grass','age'=>16,'sex'=>'女'), array('name'=>'sea','age'=>15,'birthday'=>'1987-08-16') ); print_r(getSortArray($a,'age','desc')); 结果: Array ( [0] => Array ( [name] => sunny [age] => 28 ) [1] => Array ( [name] => stone [age] => 17 [sex] => 男 ) [2] => Array ( [name] => grass [age] => 16 [sex] => 女 ) [3] => Array ( [name] => sea [age] => 15 [birthday] => 1987-08-16 ) ) 不知道你有没有看懂呢?没懂我们再看两个数组排序例子 要对数组针对age字段进行排序,php自带的简单sort功能函数,显然都不能满足需求,因此需要自己写一个快速排序代码来实现相应的需求。
代码如下 | 复制代码 | /** * Description:获取中枢点的位置 * * @param array $array * @param int $left * @param int $right * @param string $field * @return int */ function fetchArrayPivot (&$array, $left, $right, $field) { // 基准定义 $stand = $array[$left]; // 遍历数组 while ($left < $right) { while ($left < $right && $array[$right][$field] >= $stand[$field]) { $right --; } if ($left < $right) { $array[$left ] = $array[$right]; } while ($left < $right && $array[$left][$field] <= $stand[$field]) { $left ; } if ($left < $right) { $array[$right --] = $array[$left]; } } // 获取中枢点位置 $array[$left] = $stand; return $left; } /** * Description:快速排序主程序 * * @param array $array * @param int $begin * @param int $end * @param string $field */ function quickSort (&$array, $begin, $end, $field) { // 变量定义 $pivot = null; if ($begin < $end) { $pivot = fetchArrayPivot($array, $begin, $end, $field); quickSort($array, $begin, $pivot - 1, $field); quickSort($array, $pivot 1, $end, $field); } } 2,调用示例: $array = array( array( 'name' => "xiao", 'age' => 3 ), array( 'name' => 'wang', 'age' => 1 ), array( 'name' => 'chen', 'age' => 2 ), array( 'name' => 'zhengyi', 'age' => 4 ), array( 'name' => 'chai', 'age' => 14 ) ); $begin = getTime(); quickSort($array, 0, count($array) - 1, 'age'); print_r($array); $end = getTime(); $spend = $end - $begin; echo "花费时间为:".$spend."秒n"; function getTime() { list($msec, $sec) = explode(" ", microtime()); return (float)$msec (float)$sec; } |
|