朋友高分:合并两个数组

时间:2014-07-02 14:49:18

标签: php arrays facebook multidimensional-array

我在Facebook上开发游戏,并希望向用户展示朋友的高分。 什么是最有效的方法?

我有两个数组:

来自我的数据库的第一个$all包含所有玩过该游戏的用户的fbid和得分:

Array
(
    [0] => Array
        (
            [uid] => 12345
            [score] => 0
            [endgame] => 1404316845
        )

    [1] => Array
        (
            [uid] => 112873
            [score] => 0
            [endgame] => 1404334512
        )
    ...
)

来自Facebook的第二个$friends拥有所有用户的朋友:

Array
(
    [0] => Array
        (
            [uid] => 12345
            [name] => Some Name
            [pic_square] => https://...
        )

    [1] => Array
        (
            [uid] => 43324324
            [name] => Another Name
            [pic_square] => https://...
        )

    [2] => Array
        (
            [uid] => 4893424242
            [name] => Yet Another
            [pic_square] => https://...
        )
    ...
)

我认为这里首选的方法是生成一个新数组,其中只包含玩游戏且得分的朋友,如下所示:

Array
(
    [0] => Array
        (
            [uid] => 12345
            [name] => Some Name
            [pic_square] => https://...
            [score] => 0
            [endgame] => 1404316845
        )
    ...
)

我已经使用in_array尝试了各种各样的事情,但无法做到正确......有谁可以帮助我?

1 个答案:

答案 0 :(得分:1)

为由uid编制索引的分数创建新数组。

$indexedScores = [];

foreach($all as $score) {
    $indexedScores[$score['uid']] = $score['score'];
}

然后循环浏览friends数组并通过查找$indexedScores

来设置分数
foreach($friends as $key => &$friend) {
    if(isset($indexedScores[$friend['uid']])) {
        $friend['score'] = $indexedScores[$friend['uid']];
    }
    else {
        unset($friends[$key]); //doesn't have a score, so remove
    }
}

usort($friends, function($a, $b) {
    return $a['score'] > $b['score'];
});