Home  >  Article  >  Backend Development  >  Universal two-dimensional array sorting algorithm function

Universal two-dimensional array sorting algorithm function

WBOY
WBOYOriginal
2016-07-25 09:01:56932browse
Universal two-dimensional array sorting algorithm functionReprint address: http://blog.qita.in/?post=468
  1. //Two-dimensional array sorting, $arr is the data, $keys is the key value of sorting, $order is the sorting rule, 1 is ascending order, 0 is descending order
  2. function array_sort($arr, $keys, $order=0) {
  3. if (!is_array($arr)) {
  4. return false;
  5. }
  6. $keysvalue = array();
  7. foreach($arr as $key => $val) {
  8. $keysvalue[$key] = $val[$keys];
  9. }
  10. if($order == 0){
  11. asort($keysvalue);
  12. }else {
  13. arsort ($keysvalue);
  14. }
  15. reset($keysvalue);
  16. foreach($keysvalue as $key => $vals) {
  17. $keysort[$key] = $key;
  18. }
  19. $ new_array = array();
  20. foreach($keysort as $key => $val) {
  21. $new_array[$key] = $arr[$val];
  22. }
  23. return $new_array;
  24. }
  25. //eg
  26. $arr = array('0'=>array('a'=>2,'b'=>4,'c'=>3),
  27. '1'=> ;array('a'=>45,'b'=>3,'c'=>3),
  28. '2'=>array('a'=>2,'b'=> ;7,'c'=>3),
  29. );
  30. $new_array = array_sort($arr,'a',0);
  31. print_r($new_array);
Copy code


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