Home  >  Article  >  Backend Development  >  php array_multisort multidimensional array sorting example

php array_multisort multidimensional array sorting example

WBOY
WBOYOriginal
2016-07-25 09:04:10833browse
  1. $arr1 = array(1,9,5);
  2. $arr2 = array(6,2,4);
  3. array_multisort($arr1,$arr2);
  4. print_r($arr1); // get The order is 1,5,9
  5. print_r($arr2); // The order obtained is 6,4,2
Copy code

I estimate that the values ​​​​of the two arrays are corresponding from beginning to end: 1 corresponds 6 and 9 correspond to 2, and 5 corresponds to 4. Let’s see what happens if we add one more array:

  1. $arr1 = array(1,9,5);
  2. $arr2 = array(6,2,4);
  3. $arr3 = array(3,7,8);
  4. array_multisort($arr1, $arr2,$arr3);
Copy the code

View the results. 1 corresponds to 6 and 3 from beginning to end, and the same is true for other items. This correspondence is what the manual calls "preserving the original key name association during sorting". Alternatively, you can think of each array as a column in a database table. The corresponding 1,6,3 are one data row, and 9,2,7 are another data row. . . array_multisort will first sort by the first array (imagine as a column), and if the values ​​in the first array (column) are the same, then sort by the second array (column). test:

  1. $arr1 = array(1,9,5,9);
  2. $arr2 = array(6,2,4,1);
  3. $arr3 = array(3,7,8,0);
  4. array_multisort($arr1,$arr2,$arr3);
Copy code

You can imagine that the result of $arr3 here is (3,8,0,7).

2. Parameters of array_multisort.

The simplest case is to use 1 or n arrays as parameters as shown above. It should be noted that the number of items in each array must be the same, otherwise a warning will cause the sorting to fail. Like this array_multisort($arr1,$arr2,$arr3); By default, all arrays are arranged in ascending order. If you want to sort $arr2 in descending order and compare it as a string, you must write: array_multisort($arr1, $arr2, SORT_DESC, SORT_STRING, $arr3); Each array can be followed by a sort order flag, a sort type flag, or both flags at the same time. But only one sort flag of each type can appear after each array. Sort order flags: SORT_ASC - Sort in ascending order (default) SORT_DESC - Sort in descending order

Sort type flag: SORT_REGULAR - compare items normally (default) SORT_NUMERIC - Compare items numerically SORT_STRING - Compare items by string

3. The actual function of array_multisort Usually there are some multidimensional arrays that need to be sorted:

  1. $guys = Array
  2. (
  3. [0] => Array
  4. (
  5. [name] => jake
  6. [score] => 80
  7. [grade] => A
  8. )
  9. [ 1] => Array
  10. (
  11. [name] => jin
  12. [score] => 70
  13. [grade] => A
  14. )
  15. [2] => Array
  16. (
  17. [name] => ; john
  18. [score] => 80
  19. [grade] => A
  20. )
  21. [3] => Array
  22. (
  23. [name] => ben
  24. [score] => 20
  25. [grade] => B
  26. )
  27. )
Copy code

For the usage of PHP array function array_multisort(), you can also read these articles: php array functions array_map, array_multisort multidimensional array sorting examples The difference between php array sorting function array_multisort and uasort php array function array_multisort() usage Usage examples of array_multisort() in php For example, if you want to sort by grades in descending order, if the grades are the same, sort by name in ascending order. At this time we need to create two more arrays according to the order of $guys: $scores = array(80,70,80,20);$names = array('jake','jin','john','ben ');Then array_multisort($scores, SORT_DESC, $names, $guys); That's it. Can it be more flexible? Do I have to get some additional arrays every time I want to sort? In fact, it is well encapsulated in the helper_array class of qeephp. Here are its two methods. You can make slight modifications when using it:

  1. /**
  2. * 根据指定的键对数组排序
  3. *
  4. * 用法:
  5. * @code php
  6. * $rows = array(
  7. * array('id' => 1, 'value' => '1-1', 'parent' => 1),
  8. * array('id' => 2, 'value' => '2-1', 'parent' => 1),
  9. * array('id' => 3, 'value' => '3-1', 'parent' => 1),
  10. * array('id' => 4, 'value' => '4-1', 'parent' => 2),
  11. * array('id' => 5, 'value' => '5-1', 'parent' => 2),
  12. * array('id' => 6, 'value' => '6-1', 'parent' => 3),
  13. * );
  14. *
  15. * $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
  16. * dump($rows);
  17. * // 输出结果为:
  18. * // array(
  19. * // array('id' => 6, 'value' => '6-1', 'parent' => 3),
  20. * // array('id' => 5, 'value' => '5-1', 'parent' => 2),
  21. * // array('id' => 4, 'value' => '4-1', 'parent' => 2),
  22. * // array('id' => 3, 'value' => '3-1', 'parent' => 1),
  23. * // array('id' => 2, 'value' => '2-1', 'parent' => 1),
  24. * // array('id' => 1, 'value' => '1-1', 'parent' => 1),
  25. * // )
  26. * @endcode
  27. *
  28. * @param array $array 要排序的数组
  29. * @param string $keyname 排序的键
  30. * @param int $dir 排序方向
  31. *
  32. * @return array 排序后的数组
  33. */
  34. static function sortByCol($array, $keyname, $dir = SORT_ASC)
  35. {
  36. return self::sortByMultiCols($array, array($ keyname => $dir));
  37. } /**
  38. * Sort a two-dimensional array by multiple columns, similar to ORDER BY in SQL statements
  39. *
  40. * Usage:
  41. * @code php
  42. * $rows = Helper_Array::sortByMultiCols($rows, array(
  43. * ' parent' => SORT_ASC,
  44. * 'name' => SORT_DESC,
  45. * ));
  46. * @endcode
  47. *
  48. * @param array $rowset The array to be sorted
  49. * @param array $args The key to sort
  50. *
  51. * @return array Sorted array
  52. */
  53. static function sortByMultiCols($rowset, $args)
  54. {
  55. $sortArray = array();
  56. $sortRule = '';
  57. foreach ( $args as $sortField => $sortDir)
  58. {
  59. foreach ($rowset as $offset => $row)
  60. {
  61. $sortArray[$sortField][$offset] = $row[$sortField];
  62. }
  63. $sortRule .= '$sortArray['' . $sortField . ''], ' . $sortDir . ', ';
  64. }
  65. if (empty($sortArray) || empty($sortRule)) { return $rowset ; }
  66. eval('array_multisort(' . $sortRule . '$rowset);');
  67. return $rowset;
  68. }
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