Firebase查询排序不正常 [英] Firebase query ordering not working properly
问题描述
{
names:{
-KHVUwXdVPHmrO_O5kil: {
id:0,
name:Jeff
},
-KHVV7lCeac0cZNMi9fq:{
id:3 ,
name:Stig
,
-KHVVCjXgl0XxasVOHF1:{
id:13,
name: Ali
,
-KHVVJtyUO-yJZiompJO:{
id:7,
name:Hannah
},
-KHVVR8tMSO1Oh7R8tR1:{
id:2,
name:Amanda
}
}
}
,我的代码如下所示:
ref.childByAppendingPath( 名称)
.queryOrderedByChild( ID)
.observeEventType(.ChildAdded){(快照:FDataSnapshot)在
如果让myID = snapshot.value [id] as?字符串{
print(myID)
}
输出仍然在随机顺序,显示:0,2,7,1,8,4 - 这不应该是数字?我究竟做错了什么?我怎样才能对它进行排序,使其得到数字,可以是升序还是降序? 你说你是按数字排序的,但是你的 id
属性的值存储为一个字符串。
因为你将它们存储为一个字符串,它们将以字典顺序返回。
如果你想让它们按照数字顺序排列,你应该把它们存储为数字
- KHVUwXdVPHmrO_O5kil:{
id:0,
name:Jeff
},
或者,您可以将id存储为零填充字符串:
{
names :{
-KHVUwXdVPHmrO_O5kil:{
标识: 0,
名: 杰夫
},
-KHVV7lCeac0cZNMi9fq: {
id:0003,
name:Stig
},
-KHVVCjXgl0XxasVOHF1: {
id:0013,
name:Ali
},
-KHVVJtyUO-yJZiompJO:{
id: 0007,
name:Hannah
},
-KHVVR8tMSO1Oh7R8tR1:{
id:0002,
name :Amanda
}
}
}
字符串都是相同的长度,他们将按正确的顺序排序。但是你必须决定后一种解决方案中字符串/最大id值的长度,所以看起来更糟糕。
Basically I have played with Firebase for the past week, and I recently stumbled upon the 'queryOrderedByChild()' that as far as I know - allows you to sort data in firebase. However, I seem to not get the proper results. My Firebase data looks like this:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "3",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "13",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "7",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "2",
"name" : "Amanda"
}
}
}
, and my code looks like this:
ref.childByAppendingPath("names")
.queryOrderedByChild("id")
.observeEventType(.ChildAdded) { (snapshot:FDataSnapshot!) in
if let myID = snapshot.value["id"] as? String {
print(myID)
}
The output is still in a random order, displaying: 0, 2,7,1,8,4 - Isn't this supposed to be numeric? What am I doing wrong? How can I sort it so it get's numeric either ascending or descending?
You say that you're ordering by a number, but the value of your id
property is stored as a string.
Since you're storing them as a string, they will be returned in lexicographical order.
If you want them to be in numerical order, you should store them as numbers
"-KHVUwXdVPHmrO_O5kil" : {
"id" : 0,
"name" : "Jeff"
},
Alternatively, you could store the ids as zero-padded strings:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "0003",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "0013",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "0007",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "0002",
"name" : "Amanda"
}
}
}
Since the strings are all the same length, they will be sorted in the correct order. But you'll have to decide on the length of the string/maximum id value in the latter solution, so it seems worse.
这篇关于Firebase查询排序不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!