Heim  >  Artikel  >  Backend-Entwicklung  >  使用php对二维数组按数组值进行排序

使用php对二维数组按数组值进行排序

WBOY
WBOYOriginal
2016-07-25 08:41:54779Durchsuche
多维数组排序函数代码      
  1. /**
  2. * 多维数组排序
  3. * @param array $array 要排序的数组
  4. * @param string $key 排序依据字段
  5. * @param string $order 排序方式,0为降序,1为升序
  6. */
  7. function array_sort(array $array,$key,$order=1){
  8.     $sort=[];
  9. //    在此处形成字段值与键名的对应关系
  10.     foreach($array as $k=>$v){
  11.         $sort[$v[$key]]=isset($sort[$v[$key]])?array_merge($sort[$v[$key]],[$k]):[$k];
  12.     }
  13.     if($order==1&&ksort($sort)){
  14. //        升序排序
  15.     }elseif($order==0&&krsort($sort)){
  16.     }else{
  17.         return false;
  18.     }
  19.     $rs = [];
  20. //    按照排好顺序的关系生成新的数组
  21.     foreach($sort as $value){
  22.         foreach($value as $n){
  23.             $rs[] = $array[$n];
  24.         }
  25.     }
  26.     unset($sort,$array);
  27.     return $rs;
  28. }
复制代码
php


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn