Home >Backend Development >PHP Tutorial >How to sort an array based on key size
This time I will show you how to sort according to the key value size of the array, and what are the precautions for sorting according to the key value size of the array. The following is a practical case, let's take a look.
The example in this article describes how PHP implements sorting based on the size of a certain key value in the array. Share it with everyone for your reference, the details are as follows:
Question: Sort the key value of a key in a given array
Solution:
//$a是排序数组,$b是要排序的数据集合,$result是最终结果 $b = array( array('name'=>'北京','nums'=>'200'), array('name'=>'上海','nums'=>'80'), array('name'=>'广州','nums'=>'150'), array('name'=>'深圳','nums'=>'70') ); $a = array(); foreach($b as $key=>$val){ $a[] = $val['nums'];//这里要注意$val['nums']不能为空,不然后面会出问题 } //$a先排序 rsort($a); $a = array_flip($a); $result = array(); foreach($b as $k=>$v){ $temp1 = $v['nums']; $temp2 = $a[$temp1]; $result[$temp2] = $v; } //这里还要把$result进行排序,健的位置不对 ksort($result); //然后就是你想看到的结果了 var_dump($result);
Run result:
array(4) { [0]=> array(2) { ["name"]=> string(4) "北京" ["nums"]=> string(3) "200" } [1]=> array(2) { ["name"]=> string(4) "广州" ["nums"]=> string(3) "150" } [2]=> array(2) { ["name"]=> string(4) "上海" ["nums"]=> string(2) "80" } [3]=> array(2) { ["name"]=> string(4) "深圳" ["nums"]=> string(2) "70" } }
I believe you have read the case in this article After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content!
Recommended reading:
PHP implements routing and class automatic loading
Detailed explanation of the use of bindParam and bindValue in Yii2
The above is the detailed content of How to sort an array based on key size. For more information, please follow other related articles on the PHP Chinese website!