开发者

How to sort an array in php based on contained associated array?

I have an array of associative arrays:

a[0] = array("value" => "fred", "score" => 10);
a[1] = array("value" => "john", "score" => 50);
a[2] = array("value" => "paul", "score" => 5);

I would like to sort my "a" array based on the "score" value of the associated arrays开发者_StackOverflow中文版

it would become:

a[0] = array("value" => "paul", "score" => 5);
a[1] = array("value" => "fred", "score" => 10);
a[2] = array("value" => "john", "score" => 50);

Can someone please help me?


You need to use usort and a comparison function.

Something like:

function cmp($a, $b)
{
    if ($a['score'] == $b['score']) {
        return 0;
    }
    return ($a['score'] < $b['score']) ? -1 : 1;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜