<?php
$unsorted = '[{"id":"1","poi_id":"36","date":"1993-05-14","url":"#","p_flag":"0"},{"id":"2","poi_id":"36","date":"2000-05-14","url":"#","p_flag":"0"},{"id":"3","poi_id":"36","date":"1992-05-14","url":"#","p_flag":"0"}]';
function sortByYear($a, $b) {
$dA = new DateTime($a['date']);
$dB = new DateTime($b['date']);
return $dA > $dB;
}
$data=json_decode($unsorted, true);
usort($data, 'sortByYear');
print_r($data);
A few points:
You need to sort by the full year
Y
, not the last twp digitsy
. When you cross over the new millennium you have problems.I used
>
for the comparison. It is clearer what the sort is that way.usort()
sorts in place so no array is returned. This means you need to callvar_dump()
on the original array, notusort()
.