数组排序并保持按键的值 [英] Sort array and keep values of keys

查看:200
本文介绍了数组排序并保持按键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,看起来像这样:

I have an array that looks like this:

Array
(
    [team1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    [team2] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    ... many more teams
)

和我想点每支球队都有数以球队进行排序。我曾尝试这样的:

and I would like to sort the teams by the number of points each team has. I have tried this:

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

usort($this->wordswithdata, "sortbycount");

但这种方法会覆盖包含teamnames和返回键:

But that approach overrides the keys containing the teamnames and returns:

Array
(
    [0] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    [1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    etc...
)

有什么办法没有覆盖teamnames作为数组键的数组进行排序?

Is there any way to sort the array without overwriting the teamnames as the array keys?

推荐答案

使用 uasort 功能,应该保持键=>值的关联不变。

Use the uasort function, that should keep the key => value associations intact.

(侧面说明:你可以做返回$一个['点'] - $ B ['点'] 而不是IFS)

(side note: you can do return $a['points'] - $b['points'] instead of the ifs)

这篇关于数组排序并保持按键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆