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

Wich 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)?

Community
  • 1
  • 1
Maurice
  • 1,082
  • 1
  • 20
  • 43

3 Answers3

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.

Oldskool
  • 34,211
  • 7
  • 53
  • 66
0

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

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

Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56
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);
Yurii
  • 16
  • 1