在键值对中,如何根据value大小得到key的排序?
程序员文章站
2022-04-25 12:39:35
...
如:
$test={"A":1,"B":3,"C":2,"D":1,"E":1};
得到:
$result={"B":3,"C":2,"A":1,"D":1,"E":1}; 试过rsort($test),不行。 很像sql语句中的orderby,能否有办法?
回复内容:
如:
$test={"A":1,"B":3,"C":2,"D":1,"E":1};
得到:
$result={"B":3,"C":2,"A":1,"D":1,"E":1}; 试过rsort($test),不行。 很像sql语句中的orderby,能否有办法?
看看文档
>>> 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"; }
可以看下这个函数 array_multisort