Change order of JSON in PHP without key/value pair

490

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

37

Answer

Solution:

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.

390

Answer

Solution:

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

Answer

Solution:

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

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

People are also looking for solutions to the problem: php - Drupal 6 Location Module get city name using zip code

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.