This time I will bring you the method of sorting arrays according to the size of each key value in PHP. What are the precautions for sorting arrays according to the size of each key value in PHP? Here is a practical case, let's take a look.
Problem: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 mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps to implement WeChat refund application in PHP
PHP namespace namespace definition and import use case analyze
The above is the detailed content of PHP method to sort array according to key value size. For more information, please follow other related articles on the PHP Chinese website!