Home  >  Article  >  Backend Development  >  PHP two-dimensional array is sorted according to a certain field (sorting the query result set)

PHP two-dimensional array is sorted according to a certain field (sorting the query result set)

WBOY
WBOYOriginal
2016-07-25 08:48:081031browse
We often encounter sorting based on a certain key value of a two-dimensional array, and then suddenly think of a function in the onethink project, so we extract it as a reference.

2014-05-22 17::15 After reading the comments from enthusiastic phpers, I added the following:
It is recommended to use PHP’s native array_multisort() function, which will execute faster and reduce the dependence on custom functions
Official documents are difficult to explain Understand, friends who don’t understand can use
Vernacular explanation (Baidu knows): http://zhidao.baidu.com/link?url=Ljv-21fnK2CZkd03nPxb7uB7owjApdWilxZlmCcZKQqTB5AeI_BsdhyCEIaa5gWl3o9xJ2WtX8m65avJFmR9CK
  1. /**
  2. * Sort the query result set
  3. * http://www.onethink.cn
  4. * /Application/Common/Common/function.php
  5. *
  6. * @access public
  7. * @param array $list query results
  8. * @ param string $field field name for sorting
  9. * @param string $sortby sorting type (asc forward sorting desc reverse sorting nat natural sorting)
  10. * @return array
  11. */
  12. if (! function_exists('list_sort_by'))
  13. {
  14. function list_sort_by($list, $field, $sortby = 'asc')
  15. {
  16. if (is_array($ list))
  17. {
  18. $refer = $resultSet = array();
  19. foreach ($list as $i => $data)
  20. {
  21. $refer[$i] = &$data[$field];
  22. }
  23. switch ($sortby)
  24. {
  25. case 'asc': // Forward sorting
  26. asort($refer);
  27. break;
  28. case 'desc': // Reverse sorting
  29. arsort($refer);
  30. break;
  31. case 'nat': // Natural sorting
  32. natcasesort($refer);
  33. break;
  34. }
  35. foreach ($refer as $key => $val)
  36. {
  37. $resultSet[] = &$list[$key] ;
  38. }
  39. return $resultSet;
  40. }
  41. return false;
  42. }
  43. }
Copy code
  1. /**
  2. * Example
  3. * Asking: Sort in descending order according to the id key value of the two-dimensional array (that is, the larger the id is, the higher it is)?
  4. */
  5. $list = array(
  6. 0 => array(
  7. 'id' => 1,
  8. 'name' => 'first'
  9. ),
  10. 1 => array(
  11. 'id' => 3,
  12. 'name' => 'third'
  13. ),
  14. 2 => array(
  15. 'id' => 2,
  16. 'name' => ; 'Second'
  17. ),
  18. 3 => array(
  19. 'id' => 4,
  20. 'name' => 'Fourth'
  21. ),
  22. );
  23. //Answer
  24. $new_list = list_sort_by ($list, 'id', 'desc');
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
Previous article:php 的 FizzBuzzWhizzNext article:php 的 FizzBuzzWhizz