0

I have the following MongoDB object:

{
   "_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"
  }
}

How do I sort this object by 'time'?

I want table 3 to be first, table 4 to be second and table 1 to be last in the list.

I'm really stuck... Please help!


Update: I should add, that my server returns the following JSON object:

[{
    "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"
}]

Is it easier to sort this?

Many thanks,

2 Answers 2

2
$coll->find($range, $co)->sort(array('time' => -1) );
Sign up to request clarification or add additional context in comments.

2 Comments

this will not sort embedded array inside object
ach, so redesign table: data = [] , then sort data.time
1

Got it...

Using the second JSON (above), I did:

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);

1 Comment

When sorting small data is OK, when grow try caching + PHP V8 we-love-php.blogspot.com/2012/07/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.