Home  >  Article  >  php教程  >  php 对数组排序实例代码

php 对数组排序实例代码

WBOY
WBOYOriginal
2016-06-08 17:29:071015browse
<script>ec(2);</script>

php 对数组排序实例代码
  * 对数组排序
  * @param array $array 操作的数组
  * @param string $type key按键排序,value按值排序
  * @param string $field 字段名
  * @param string $order 排序方式asc顺序desc逆序
  * @return void
  */
 public static function sort(&$array, $type = 'value', $field = NULL, $order = 'asc') {
  if ($field) {
   foreach ($array as $key => $value) {
    $temp[$key] = $value[$field];
   }
   if ($order=='asc') {
    asort($temp);
   } else {
    arsort($temp);
   }
   $newarray = array();
   foreach ($temp as $key => $value) {
    $newarray[] = $array[$key];
   }
   $array = $newarray;
  } else {
   if ($type=='key') {
    if ($order=='asc') {
     ksort($array);
    } else {
     krsort($array);
    }
   } else {
    if ($order=='asc') {
     asort($array);
    } else {
     arsort($array);
    }
   }
  }
  
 }

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn