This article mainly introduces the method of PHP programming to implement multi-dimensional array sorting according to a certain key value. It analyzes the two sorting operation methods of array_multisort and array_sort in the form of examples. Friends in need can refer to this article
The example describes how to implement PHP programming to sort multi-dimensional arrays according to a certain key value. Share it with everyone for your reference, the details are as follows:
Two solutions to achieve sorting multi-dimensional arrays according to a certain key value (array_multisort
and array_sort
):
First type:
array_multisort()
The function sorts multiple arrays or multi-dimensional arrays.
//对数组$hotcat按照count键值大小降序进行排序; $hotcat =array( array('1501'=>array('catid'=>'1546','catname'=>'数组排序 一级','count'=>'588')), array('1501'=>array('catid'=>'1546','catname'=>'数组排序二级','count'=>'588')), array('1501'=>array('catid'=>'1546','catname'=>'数组排序 三级','count'=>'588')) ); //提取列数组; foreach ($hotcat as $key => $val) { $tmp[$key] = $row['username']; } array_multisort($tmp,SORT_DESC,$hotcat);此处对数组进行降序排列;SORT_DESC按降序排列
Second type:
Custom methodarray_sort()
Sort
//指定数组以$keys键值排序 function array_sort($array,$keys,$type='asc'){ //$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序 $keysvalue = $new_array = array(); foreach ($array as $k=>$v){ $keysvalue[$k] = $v[$keys]; } if($type == 'asc'){ asort($keysvalue); }else{ arsort($keysvalue); } reset($keysvalue); foreach ($keysvalue as $k=>$v){ $new_array[$k] = $array[$k]; } return $new_array; } $hot_cat = array_sort($hot_cat,'count','desc'); //此处对数组进行降序排列
Picture 1:
##Picture 2:Warm reminder:As can be seen from the above figure, the first method has a drawback. If your array is a string key name, it will be retained, but the numeric key will be re-indexed, starting from 0. and increments by 1. So when the array is sorted and all previous key names need to be retained, it is recommended to use the second method.
The above is the entire content of this article, I hope it will be helpful to everyone's learning.php simple method to get the check box value_php tips
Definition and usage of php similar_text() function_php skills
phpwind puts automatic registration method_javascript skills
The above is the detailed content of PHP method to implement multi-dimensional array sorting according to a certain key value. For more information, please follow other related articles on the PHP Chinese website!