Home > Backend Development > PHP Tutorial > PHP sorts array according to the size of a certain key value

PHP sorts array according to the size of a certain key value

小云云
Release: 2023-03-21 10:38:02
Original
2535 people have browsed it

This article mainly introduces to you the method of PHP to sort according to the size of a certain key value of the array, involving PHP's operation skills for array traversal, sorting and other related operations. Friends who need it can refer to it. I hope it can help you.

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

Running 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

Related recommendations:

Examples of commonly used sorting implementation methods in php

Detailed explanation of php bubbling, selection, insertion and quick sorting methods

php implementation A common sorting algorithm

The above is the detailed content of PHP sorts array according to the size of a certain key value. 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