PHP method to sort array according to key value size

php中世界最好的语言
Release: 2023-03-26 14:18:01
Original
2666 people have browsed it

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);
Copy after login

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"
 }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!