I have the following data that I've built (simplified for example) and am having trouble sorting the data by [start_date] in PHP - any help for be very much appreciated thank you as I'm pulling my hair out with usort etc!!
[1338] => Array
(
[0] => stdClass Object
(
[id] => 193
[data] => 1338
[num] => 2
)
[start_date] => 2014-09-13
)
[618] => Array
(
[0] => stdClass Object
(
[id] => 193
[data] => 1338
[num] => 2
)
[1] => stdClass Object
(
[id] => 193
[data] => 1338
[num] => 2
)
[start_date] => 2014-06-20
)
[349] => Array
(
[0] => stdClass Object
(
[id] => 887
[data] => 223
[num] => 2
)
[1] => stdClass Object
(
[id] => 887
[data] => 224
[num] => 2
)
[start_date] => 2014-08-20
)
try this
function cmp($a, $b){
$a = strtotime($a['start_date']);
$b = strtotime($b['start_date']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");
usort is the way to go:
usort($array, function($a,$b){
return strtotime($a["start_date"]) - strtotime($b["start_date"]);
});
Shakti Patel's answer basically worked (thank you sir!) - but I needed to retain the original indexes (I should have made this more clearer in my original question) - so here is the example where I use uasort() which maintains the indexes:
function cmp($a, $b){
$a = strtotime($a['start_date']);
$b = strtotime($b['start_date']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
uasort($array, "cmp");