0

我有以下 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"
}]

排序更容易吗?

非常感谢,

4

2 回答 2

2
$coll->find($range, $co)->sort(array('time' => -1) );
于 2012-11-03T17:39:12.100 回答
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);
于 2012-11-03T18:06:54.067 回答