Php 按最高键对数组排序=>;价值

Php 按最高键对数组排序=>;价值,php,arrays,Php,Arrays,我想按amount的值对数组进行从高到低的排序。我的数组$res如下所示: Array ( [0] => 1 [id] => 1 [1] => Testowy 1 [user] => Testowy 1 [2] => 150 [amount] => 150 [3] => 1,2,3 [what] => 1,2,3 [4] => Polska [country] =

我想按
amount
的值对数组进行从高到低的排序。我的数组
$res
如下所示:

Array
(
    [0] => 1
    [id] => 1
    [1] => Testowy 1
    [user] => Testowy 1
    [2] => 150
    [amount] => 150
    [3] => 1,2,3
    [what] => 1,2,3
    [4] => Polska
    [country] => Polska
    [5] => 1
    [platform] => 1
)
Array
(
    [0] => 2
    [id] => 2
    [1] => Testowy 2
    [user] => Testowy 2
    [2] => 100
    [amount] => 100
    [3] => 1
    [what] => 1
    [4] => United States
    [country] => United States
    [5] => 2
    [platform] => 2
)

我试着使用
max
arsort
,但它们似乎都不接受应该使用哪个键进行排序。有什么帮助吗?

使用带有用户定义比较器的排序功能,如:usort:

然后,比较器得到两个对象,并告诉(通过您想要的任何逻辑)哪一个更大:

试试usort

function cmp($a, $b)
{
    return ($a["amount"]<=$b["amount"])?-1:1;
}

usort($array, "cmp");
函数cmp($a,$b)
{
回报($a[“金额”]
对于PHP<5.3的版本,请使用以下命令:

function cmp($a, $b){
    return $b['amount'] - $a['amount'];
}
usort($res, "cmp");

?我只是在这里猜测,但是如果这个结果是db查询的结果,您也可以在查询中使用排序,例如,
$a1
->
($a1,$b)
中的
1
($a1,$b)
输入错误?过多。最简单的函数体:
返回($a[“amount”]>=$b[“amount”])
=
@dognose:不。这是新手应该理解的答案。没有地方耍花招也许不用strcmp,但一个简单的“>”因为amount根本就不是字符串。排序“1”和“10”可能是错误的。现在你缺少了相同的大小写:)
return($a[“amount”]>=$b[“amount”])
=
我尝试了
usort
,但我得到了
usort()期望参数1是数组,给定的布尔值
来自
而($res=mysql\u fetch\u array($query))
mysql\u fetch\u array
不是在返回数组吗?@TomekBuszewski-应该是这样的,但是你不会得到这样的错误,除非你试图给
usort
一个布尔值。你为什么不尝试转储
$res
看看你得到了什么。我使用了
print\r($res)
,并将它粘贴到我的问题中。
usort($res, function ($a, $b){
    return $b['amount'] - $a['amount'];
});
print_r($res);
function cmp($a, $b){
    return $b['amount'] - $a['amount'];
}
usort($res, "cmp");