Home > Backend Development > PHP Tutorial > In key-value pairs, how to get the sorting of keys based on value size?

In key-value pairs, how to get the sorting of keys based on value size?

不言
Release: 2023-03-03 08:00:01
Original
1600 people have browsed it


For example:

 $test={"A":1,"B":3,"C":2,"D":1,"E":1};
Copy after login
Copy after login

Get:

$result={"B":3,"C":2,"A":1,"D":1,"E":1};

试过rsort($test),不行。
很像sql语句中的orderby,能否有办法?
Copy after login
Copy after login

Reply content:

For example:

 $test={"A":1,"B":3,"C":2,"D":1,"E":1};
Copy after login
Copy after login

Get:

$result={"B":3,"C":2,"A":1,"D":1,"E":1};

试过rsort($test),不行。
很像sql语句中的orderby,能否有办法?
Copy after login
Copy after login

Look at the document

>>> arsort($test)
>>> $test
=> [
     "B" => 3,
     "c" => 2,
     "e" => 1,
     "d" => 1,
     "A" => 1,
   ]
Copy after login
function cmp($a, $b)
{
if ($a == $b) {
    return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
Copy after login

You can take a look at this function array_multisort

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