Home >Backend Development >PHP Tutorial >PHP code to sort a two-dimensional array by specified key value

PHP code to sort a two-dimensional array by specified key value

WBOY
WBOYOriginal
2016-07-25 09:00:441042browse
  1. //二维数组 按键值 排序
  2. function array_sort($array,$keys,$type='desc'){
  3. if(!isset($array) || !is_array($array) || empty($array)){
  4. return '';
  5. }
  6. if(!isset($keys) || trim($keys)==''){
  7. return '';
  8. }
  9. if(!isset($type) || $type=='' || !in_array(strtolower($type),array('asc','desc'))){
  10. return '';
  11. }
  12. $keysvalue=array();
  13. foreach($array as $key=>$val){
  14. $val[$keys] = str_replace('-','',$val[$keys]);
  15. $val[$keys] = str_replace(' ','',$val[$keys]);
  16. $val[$keys] = str_replace(':','',$val[$keys]);
  17. $keysvalue[] =$val[$keys];
  18. }
  19. asort($keysvalue); //key值排序
  20. reset($keysvalue); //指针重新指向数组第一个
  21. foreach($keysvalue as $key=>$vals) {
  22. $keysort[] = $key;
  23. }
  24. $keysvalue = array();
  25. $count=count($keysort);
  26. if(strtolower($type) != 'asc'){
  27. for($i=$count-1; $i>=0; $i--) {
  28. $keysvalue[] = $array[$keysort[$i]];
  29. }
  30. }else{
  31. for($i=0; $i<$count; $i++){
  32. $keysvalue[] = $array[$keysort[$i]];
  33. }
  34. }
  35. return $keysvalue;
  36. } //by bbs.it-home.org
  37. ?>
复制代码

>>> 更多内容,请查看 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