PHP / MongoDB - 按时间排序

时间:2012-11-03 17:28:40

标签: php mongodb

我有以下MongoDB对象:

{
   "_id": ObjectId("50954f0d13f88da4a590e5ff"),
   "uname": "Eamorr",
   "1": {
     "table": "1",
     "color": "red",
     "time": NumberInt(1351963491),
     "niceTime": "2012-11-03T17: 24: 51+00: 00"
  },
   "3": {
     "table": "3",
     "color": "green",
     "time": NumberInt(1351963567),
     "niceTime": "2012-11-03T17: 26: 07+00: 00"
  },
   "4": {
     "table": "4",
     "color": "orange",
     "time": NumberInt(1351963506),
     "niceTime": "2012-11-03T17: 25: 06+00: 00"
  }
}

如何按“时间”排序此对象?

我希望table 3成为第一个,table 4成为第二个,table 1成为列表中的最后一个。

我真的被困了......请帮忙!


更新: 我应该补充一点,我的服务器返回以下JSON对象:

[{
    "table": "4",
    "color": "orange",
    "time": 1351965770,
    "niceTime": "2012-11-03T18:02:50+00:00"
}, {
    "table": "3",
    "color": "red",
    "time": 1351964379,
    "niceTime": "2012-11-03T17:39:39+00:00"
}, {
    "table": "1",
    "color": "red",
    "time": 1351964997,
    "niceTime": "2012-11-03T17:49:57+00:00"
}]

对此进行排序更容易吗?

非常感谢,

2 个答案:

答案 0 :(得分:2)

$coll->find($range, $co)->sort(array('time' => -1) );

答案 1 :(得分:1)

得到了......

使用第二个JSON(上面),我做了:

function my_sort($a, $b){
    if ($a['time'] > $b['time']) {
        return -1;
    } else if ($a['time'] < $b['time']) {
        return 1;
    } else {
        return 0;
    }
}

usort($obj,'my_sort');
echo json_encode($obj);