开发者

How Sort a multidimensional (json) array with PHP

Can someone help me please ... I've read previous PHP 'sorting' questions ... and tried to follow the logic ... but brain fade prevails ;-!

I have a json object (from facebook) which I am trying to sort using one of the values ('created_time') using the following code:

$json = file_get_cont开发者_如何学Goents($url,0,null,null);
$result = json_decode($json, true);
array_multisort($note['created_time'], SORT_ASC, $result);   /* what's wrong with this line?? */

Example json data shown below:

{
   "data": [
      {
         "id": "123",
         "from": {
            "name": "Example",
            "category": "Musician/band",
            "id": "123"
         },
         "subject": "Subject 1",
         "message": "Example message text 1",
         "created_time": "2011-07-12T20:18:17+0000",
      },
      {
         "id": "123",
         "from": {
            "name": "Example",
            "category": "Musician/band",
            "id": "123"
         },
         "subject": "Subject 2",
         "message": "Example message text 2",
         "created_time": "2011-07-12T20:21:01+0000",
      },
...

Thanks for you help.


Your PHP snippet references a $note object but I just see the $json and $result variables...

Assuming we have the data array available you can use usort with a custom function.. this could be an anonymous function if you are using PHP 5.3+

function sort_by_creation($a, $b) 
{
  return (strtotime($a['created_time']) < strtotime($b['created_time']) ? -1 : 1;
}
usort($data, 'sort_by_creation');


I'm not sure if that will work. Where does $note come from? If you are trying to sort an array by a specific member, what about usort? http://php.net/manual/en/function.usort.php

so something like:

function sortByCreatedTime($a, $b){
  if ($strtotime($a['data']['created_time']) == strtotime($b['data']['created_time'])) {
    return 0;
  };
  return ($strtotime($a['data']['created_time']) < strtotime($b['data']['created_time'])) ? -1 : 1;
};
usort($result, sortByCreatedTime);
for($i = 0; $i < count($results['data']); $i++){
  //should output in descending order.  if not just change 
  //the < to a > in the sort function above
  echo 'time is => ' . $results['data']['created_time'] . '<br>';
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜