通过2个键对FireBase中的数据进行排序 [英] Sort data from FireBase by 2 keys

查看:53
本文介绍了通过2个键对FireBase中的数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了游戏应用程序,并将记录保存在FireBase的实时数据库中. 数据库外观:

I built game app and I save records on real time database of FireBase. the database look:

{
    "Ka8xxTgyFB8yYKH50j" : {
        "score" : 10,
        "seconds" : 1325
    },
    "K222xTgyFBF33FD50j" : {
        "score" : 10,
        "seconds" : 425
    },
    "Ka32T23R328yYKH50j" : {
        "score" : 5,
        "seconds" : 115
    },
    "F323F32FB8yYKH50j" : {
        "score" : 30,
        "seconds" : 2335
    }
    }
}

我想从FireBase中获取数据,然后按分数排序,然后按秒排序. 在此示例中,数据的正确顺序应为:

I want to get the data from FireBase sorted by score, and then sort by seconds. the right order of the data in this example should to be:

得分:5秒:115

得分:10秒:425

score:10 seconds:425

得分:10秒:1325

score:10 seconds:1325

得分:30秒:2335

score:30 seconds:2335

如何通过其他方式使用orderByChild来做到这一点? 谢谢

How can I do this using orderByChild ot other way? thank you

推荐答案

由于firebase不允许进行多重排序,因此我建议您创建一个排序列并根据您的排序要求对其进行更新. 在您的情况下,您可以将秒和分数连接起来,然后将其存储为整数.为了提供一致的长度,必须用0填充秒,以便说6个字符(取决于您的分数和最大可能的秒数). 可以说,最高分是100,最大秒数是50000,您的排序顺序是score5 chars of seconds的组合,强制转换为整数.

Since firebase does not allow multi-sort, I recommend you to create a sort column and update it according to your sorting requirement. In your case, you can concatenate the seconds and score, then store it as integer. To give it consistent length, seconds must be str padded with 0 for lets say 6 chars (depends on your score and seconds max possible values). Lets say, maximum score is 100, and max seconds are 50000, your sort order would be combination of score and 5 chars of seconds, casted as integer.

示例:

{
    "Ka8xxTgyFB8yYKH50j" : {
        "score" : 10,
        "seconds" : 1325,
        "sort_order": 1001325
    },
    "K222xTgyFBF33FD50j" : {
        "score" : 10,
        "seconds" : 425,
        "sort_order": 1000425
    },
    "Ka32T23R328yYKH50j" : {
        "score" : 5,
        "seconds" : 115
        "sort_order": 5000115
    },
    "F323F32FB8yYKH50j" : {
        "score" : 30,
        "seconds" : 2335,
        "sort_order": 3002335
    }
}

这样,您可以按升序和降序对它进行快速排序.

This way, you can sort it very fast in both ascending and descending orders.

这篇关于通过2个键对FireBase中的数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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