PHP two-dimensional array is sorted according to a certain field (sorting the query result set)
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-25 08:48:08
Original
1115 people have browsed it
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
- /**
- * Sort the query result set
- * http://www.onethink.cn
- * /Application/Common/Common/function.php
- *
- * @access public
- * @param array $list query results
- * @ param string $field field name for sorting
- * @param string $sortby sorting type (asc forward sorting desc reverse sorting nat natural sorting)
- * @return array
- */
- if (! function_exists('list_sort_by'))
- {
- function list_sort_by($list, $field, $sortby = 'asc')
- {
- if (is_array($ list))
- {
- $refer = $resultSet = array();
- foreach ($list as $i => $data)
- {
- $refer[$i] = &$data[$field];
- }
- switch ($sortby)
- {
- case 'asc': // Forward sorting
- asort($refer);
- break;
- case 'desc': // Reverse sorting
- arsort($refer);
- break;
- case 'nat': // Natural sorting
- natcasesort($refer);
- break;
- }
- foreach ($refer as $key => $val)
- {
- $resultSet[] = &$list[$key] ;
- }
- return $resultSet;
- }
- return false;
- }
- }
Copy code
- /**
- * Example
- * 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)?
- */
- $list = array(
- 0 => array(
- 'id' => 1,
- 'name' => 'first'
- ),
- 1 => array(
- 'id' => 3,
- 'name' => 'third'
- ),
- 2 => array(
- 'id' => 2,
- 'name' => ; 'Second'
- ),
- 3 => array(
- 'id' => 4,
- 'name' => 'Fourth'
- ),
- );
- //Answer
- $new_list = list_sort_by ($list, 'id', 'desc');
Copy code
|
Statement of this Website
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
Latest Articles by Author
-
2025-02-26 03:58:14
-
2025-02-26 03:38:10
-
2025-02-26 03:17:10
-
2025-02-26 02:49:09
-
2025-02-26 01:08:13
-
2025-02-26 00:46:10
-
2025-02-25 23:42:08
-
2025-02-25 22:50:13
-
2025-02-25 21:54:11
-
2025-02-25 20:45:11
Latest Issues
-
2025-03-26 12:24:37
-
2025-03-26 12:20:46
-
2025-03-21 13:39:34
-
2025-03-21 13:38:34
-
2025-03-21 13:37:19