Home  >  Article  >  Backend Development  >  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?

不言
不言Original
2018-05-18 09:21:131559browse


For example:

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

Get:

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

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

Reply content:

For example:

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

Get:

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

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

Look at the document

>>> arsort($test)
>>> $test
=> [
     "B" => 3,
     "c" => 2,
     "e" => 1,
     "d" => 1,
     "A" => 1,
   ]
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";
}

You can take a look at this function array_multisort

Statement:
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