PHP 多維陣列進行排序

來源:互聯網
上載者:User
  1. /*
  2. function:二維數組按指定的索引值排序
  3. $array=array(
  4. 0=>array('id'=>8,'username'=>'phpernote'),
  5. 1=>array('id'=>9,'username'=>'com'),
  6. 2=>array('id'=>5,'username'=>'www')
  7. );
  8. 現在需要將這個二維數組按id升序排列,則:
  9. array_sort($array,'id','asc');
  10. */
  11. public function array_sort($array,$keys,$type='asc'){
  12. if(!isset($array) || !is_array($array) || empty($array)){
  13. return '';
  14. }
  15. if(!isset($keys) || trim($keys)==''){
  16. return '';
  17. }
  18. if(!isset($type) || $type=='' || !in_array(strtolower($type),array('asc','desc'))){
  19. return '';
  20. }
  21. $keysvalue=array();
  22. foreach($array as $key=>$val){
  23. $val[$keys] = str_replace('-','',$val[$keys]);
  24. $val[$keys] = str_replace(' ','',$val[$keys]);
  25. $val[$keys] = str_replace(':','',$val[$keys]);
  26. $keysvalue[] =$val[$keys];
  27. }
  28. asort($keysvalue); //key值排序
  29. reset($keysvalue); //指標重新指向數組第一個
  30. foreach($keysvalue as $key=>$vals) {
  31. $keysort[] = $key;
  32. }
  33. $keysvalue = array();
  34. $count=count($keysort);
  35. if(strtolower($type) != 'asc'){
  36. for($i=$count-1; $i>=0; $i--) {
  37. $keysvalue[] = $array[$keysort[$i]];
  38. }
  39. }else{
  40. for($i=0; $i<$count; $i++){
  41. $keysvalue[] = $array[$keysort[$i]];
  42. }
  43. }
  44. return $keysvalue;
  45. }
複製代碼
PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.