php自定义二维数组排序函数array_orderby用法示例

这篇文章主要介绍了php自定义二维数组排序函数array_orderby用法,结合实例形式分析了php针对二维数组进行排序的相关遍历、判定、排序等操作技巧,需要的朋友可以参考下。

本文实例讲述了php自定义二维数组排序函数array_orderby用法,分享给大家供大家参考,具体如下:

  1. <?php
  2. /**
  3. I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().
  4. */
  5. function array_orderby()
  6. {
  7. $args = func_get_args();
  8. $data = array_shift($args);
  9. foreach ($args as $n => $field) {
  10. if (is_string($field)) {
  11. $tmp = array();
  12. foreach ($data as $key => $row)
  13. $tmp[$key] = $row[$field];
  14. $args[$n] = $tmp;
  15. }
  16. }
  17. $args[] = &$data;
  18. call_user_func_array('array_multisort', $args);
  19. return array_pop($args);
  20. }
  21. /*
  22. The sorted array is now in the return value of the function instead of being passed by reference.
  23. */
  24. $data[] = array('volume' => 67, 'edition' => 2);
  25. $data[] = array('volume' => 86, 'edition' => 1);
  26. $data[] = array('volume' => 85, 'edition' => 6);
  27. $data[] = array('volume' => 98, 'edition' => 2);
  28. $data[] = array('volume' => 86, 'edition' => 6);
  29. $data[] = array('volume' => 67, 'edition' => 7);
  30. // Pass the array, followed by the column names and sort flags
  31. $sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
  32. print_r($sorted)
  33. ?>

运行结果:

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [volume] => 98
  6. [edition] => 2
  7. )
  8. [1] => Array
  9. (
  10. [volume] => 86
  11. [edition] => 1
  12. )
  13. [2] => Array
  14. (
  15. [volume] => 86
  16. [edition] => 6
  17. )
  18. [3] => Array
  19. (
  20. [volume] => 85
  21. [edition] => 6
  22. )
  23. [4] => Array
  24. (
  25. [volume] => 67
  26. [edition] => 2
  27. )
  28. [5] => Array
  29. (
  30. [volume] => 67
  31. [edition] => 7
  32. )
  33. )