cgimusic Posted December 6, 2009 Share Posted December 6, 2009 Hi guys. I have a list of TV show episodes and air dates in the form of $episodes[x]["airdate"]=yyyy-mm-dd but I don't know how to sort the episodes by their air dates. Here is the code I attempted to use to sort by year but it doesn't seem to work. The episode order appears to be basically random. <?php function recordcompare($record1,$record2){ return strnatcmp($record1,$record2); }; usort($episodes,"recordcompare"); ?> Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/ Share on other sites More sharing options...
salathe Posted December 6, 2009 Share Posted December 6, 2009 You need to use the values for the airdates in the comparison like return strnatcmp($a["airdate"], $b["airdate"]); Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/#findComment-972399 Share on other sites More sharing options...
cgimusic Posted December 6, 2009 Author Share Posted December 6, 2009 I'm still not getting the right result. The first four results are: 2008-09-23 2008-09-30 2008-10-14 2008-09-16 Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/#findComment-972413 Share on other sites More sharing options...
.josh Posted December 6, 2009 Share Posted December 6, 2009 http://us.php.net/manual/en/function.array-multisort.php#51695 Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/#findComment-972432 Share on other sites More sharing options...
cgimusic Posted December 6, 2009 Author Share Posted December 6, 2009 http://us.php.net/manual/en/function.array-multisort.php#51695 Works great. I don't see why my code with salathe's modification didn't work but thanks for fixing the problem. Final code: <?php foreach($episodes as $episode){ $temp289[]=$episode["airdate"]; }; array_multisort($temp289,SORT_ASC,$episodes); ?> Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/#findComment-972459 Share on other sites More sharing options...
salathe Posted December 6, 2009 Share Posted December 6, 2009 I'm still not getting the right result. The first four results are: 2008-09-23 2008-09-30 2008-10-14 2008-09-16 Perhaps it's time for a more complete snippet so we can see how you're using the values? While you're doing that, this one works as expected: $episodes[1]['airdate'] = '2008-10-14'; $episodes[2]['airdate'] = '2008-09-16'; $episodes[3]['airdate'] = '2008-09-30'; $episodes[4]['airdate'] = '2008-09-23'; function recordcompare($a, $b) { return strnatcmp($a['airdate'], $b['airdate']); } uasort($episodes, 'recordcompare'); print_r($episodes); Quote Link to comment https://forums.phpfreaks.com/topic/184181-sorting-an-array/#findComment-972479 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.