开发者

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

开发者 https://www.devze.com 2023-02-09 08:24 出处:网络
I have an array of associative arrays: a[0] = array(\"value\" => \"fred\", \"score\" => 10); a[1] = array(\"value\" => \"john\", \"score\" => 50);

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

精彩评论

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