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
|