English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article example explains how to sort a specific key of a two-dimensional array in PHP. Shared for everyone's reference, as follows:
/** * Sort the query result set * @access public * @param array $list Query results * @param string $field Name of the field to sort by * @param string $sortby Sorting type (asc for ascending order, desc for reverse order, nat for natural order) * @return array */ 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': // Ascending 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 * Question: How to sort the id key of a two-dimensional array in descending order (that is, the larger the id, the earlier it is placed)? */ $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'); print_r($new_list);
Running results are as follows:
Array ( [0] => Array ( [id] => 4 [name] => Fourth ) [1] => Array ( [id] => 3 [name] => Third ) [2] => Array ( [id] => 2 [name] => Second ) [3] => Array ( [id] => 1 [name] => First ) )
More about PHP-related content, readers who are interested can view the special topic of this site: 《PHP Array (Array) Operation Skills大全》、《PHP Basic Syntax Tutorial》、《PHP Operation and Operator Usage Summary》、《PHP Object-Oriented Program Design Tutorial》、《PHP Network Programming Skills Summary》、《PHP String (string) Usage Summary》、《php+MySQL Database Operation Tutorial》and《PHP Common Database Operation Skills Summary}
I hope this article will be helpful to everyone in PHP program design.
Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any suspected copyright content, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.)