0

I have a situation where I need to sort a JSON object by date. I've searched for solutions online and everything points in the direction of PHP's usort function, but all examples have a key/value pair to sort on.

This is how I load the feed:

$ret = file_get_contents($url);
$res = json_encode($ret);

Which results in the following JSON

{  
   "2015-12-14":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
  },
   "2015-12-15":{  
      "direction":"S",
      "snowfall":3.0,
      [..]
   },
   "2015-12-12":{  
      "direction":"SE",
      "snowfall":0.0,
      [..]
   },
   "2015-12-13":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   },
   "2015-12-10":{  
      "direction":"E",
      "snowfall":0.0,
      [..]
   },
   "2015-12-11":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   }
}

As you can see, the data is not properly ordered by date, but the date value is the key so how can I sort the object by date (2015-12-10, 2015-12-11, 2015-12-12, 2015-12-13, 2015-12-14, 2015-12-15)?

3 Answers 3

1

Just sort the data before encoding it, with something like ksort:

$ret = file_get_contents($url);
ksort($ret);
$res = json_encode($ret);

That way, the array that $ret seems to return will be sorted by key (the date) and then be encoded in that sorted order.

Sign up to request clarification or add additional context in comments.

Comments

0
$json = '{  
   "2015-12-14":{  

      "direction":"S",

      "snowfall":0.0

  },

   "2015-12-15":{  

      "direction":"S",

      "snowfall":3.0

   },

   "2015-12-12":{  

      "direction":"SE",

      "snowfall":0.0

   },

   "2015-12-13":{  

      "direction":"S",

      "snowfall":0.0

   },

   "2015-12-10":{  

      "direction":"E",

      "snowfall":0.0

   },

   "2015-12-11":{  

      "direction":"S",

      "snowfall":0.0

   }

}';

$array = get_object_vars(json_decode($json));

ksort($array);

echo json_encode((object)$array);

Comments

0

You can use ksort, which can sort your array by key.

You can use sort flags as well, which are well-described here.

Comments

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.