Php two-dimensional array sorting by a field (sorting the query result set)
We often encounter sorting by a key value of a two-dimensional array, and then suddenly think of a function in the onethink project, so it is extracted for reference.
: 15 I saw the enthusiastic phper comments and added the following content: We recommend that you use the native array_multisort () function of php. the execution speed is faster and the dependency of custom functions is reduced. It is hard to understand the official documentation and can be used by friends who do not understand it. Big vernacular (Baidu know): http://zhidao.baidu.com/link? Url = Ljv-21fnK2CZkd03nPxb7uB7owjApdWilxZlmCcZKQqTB5AeI_BsdhyCEIaa5gWl3o9xJ2WtX8m65avJFmR9CK
- /**
- * Sort query result sets.
- * Http://www.onethink.cn
- */Application/Common/function. php
- *
- * @ Access public
- * @ Param array $ list query result
- * @ Param string $ field name of the field to be sorted
- * @ Param string $ sortby sorting type (asc positive 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 ': // positive 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;
- }
- }
- /**
- * Example
- * Q: is the key value of the two-dimensional array sorted in descending order (that is, the bigger the id, the more advanced )?
- */
- $ List = array (
- 0 => array (
- 'Id' => 1,
- 'Name' => '1'
- ),
- 1 => array (
- 'Id' => 3,
- 'Name' => '3'
- ),
- 2 => array (
- 'Id' => 2,
- 'Name' => '2'
- ),
- 3 => array (
- 'Id' => 4,
- 'Name' => '4'
- ),
- );
- // Answer
- $ New_list = list_sort_by ($ list, 'id', 'desc ');
|