Home  >  Article  >  Backend Development  >  PHP multidimensional array sorting

PHP multidimensional array sorting

WBOY
WBOYOriginal
2016-07-25 08:42:52923browse
  1. /*
  2. function: Sort the two-dimensional array by the specified key value
  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. Now we need to sort this two-dimensional array in ascending order by id, then:
  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 value sorting
  29. reset($keysvalue); //Repoint the pointer to the first one in the array
  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. }
Copy code

PHP


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