TripleDES Posted June 13, 2007 Share Posted June 13, 2007 Let's say I have 3 elements in my array: [0] = apple [1] = orange [2] = 06/12/2007 How do I go about sorting by date using the 3rd element? Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/ Share on other sites More sharing options...
Barand Posted June 13, 2007 Share Posted June 13, 2007 First step is to choose a date format that can be sorted. Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/#findComment-273669 Share on other sites More sharing options...
TripleDES Posted June 13, 2007 Author Share Posted June 13, 2007 Yes, no problem there. I'll convert the entered date into epoch. But how do I sort by the third value in the array? Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/#findComment-273830 Share on other sites More sharing options...
Barand Posted June 13, 2007 Share Posted June 13, 2007 Custom sort function and usort() <?php function mysort($a, $b) { if ($a[2] == $b[2]) return 0; return ($a[2] < $b[2]) ? -1 : 1; } $ar = array ( array ('apple', 'orange', '2007-06-13'), array ('kiwi', 'pear', '2007-04-10'), array ('banana', 'nectarine', '2007-05-10') ); usort ($ar, 'mysort'); // check results echo '<pre>', print_r($ar, true), '</pre>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/#findComment-273846 Share on other sites More sharing options...
TripleDES Posted June 14, 2007 Author Share Posted June 14, 2007 Thank you! Please explain the function you created so I can understand. Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/#findComment-274352 Share on other sites More sharing options...
Barand Posted June 14, 2007 Share Posted June 14, 2007 http://www.php.net/manual/en/function.usort.php Quote Link to comment https://forums.phpfreaks.com/topic/55371-sort-array-by-third-value-date/#findComment-274455 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.