Guardian-Mage Posted August 14, 2008 Share Posted August 14, 2008 Array ( [0] => Array ( [0] => Advanced PHP for Web Professionals [1] => [2] => Compiled HTML [3] => 2002 [4] => ) [1] => Array ( [0] => Creating Cool Web Sites With HTML, XHTML, And CSS [1] => [2] => Portable Document Format [3] => 2004 [4] => ) [2] => Array ( [0] => CSS Hacks & Filters - Making Cascading Stylesheets Work [1] => [2] => Portable Document Format [3] => 2005 [4] => ) [3] => Array ( [0] => CSS Web Design for Dummies [1] => [2] => Portable Document Format [3] => 2005 [4] => ) [4] => Array ( [0] => HTML 4 For Dummies, 5th Edition [1] => [2] => Portable Document Format [3] => 2005 [4] => ) [5] => Array ( [0] => HTML In 10 Simple Steps Or Less [1] => [2] => Portable Document Format [3] => 2004 [4] => ) [6] => Array ( [0] => HTML Mastery - Semantics, Standards, And Styling [1] => [2] => Portable Document Format [3] => 2006 [4] => ) [7] => Array ( [0] => HTML, XHTML, & CSS Bible [1] => 3rd Edition [2] => Portable Document Format [3] => 2004 [4] => Brian Pfaffenberger ) ) How would I sort the above array by the date field ([3]). I have read about arsort and sort and all of them but I don't quite understand it. Help is greatly appreciated. Quote Link to comment Share on other sites More sharing options...
BioBob Posted August 14, 2008 Share Posted August 14, 2008 array_multisort(); Sorry I dont have any easy examples, thats kind of a pain to work with for me and I dont mess with it much... Probably some good ones on php.net tho... Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 14, 2008 Share Posted August 14, 2008 I prefer to use usort() (or uasort() if you need to maintain index associations). This is especially helpful with multidimensional arrays where you may need to add more logic than just simple sorting. <?php function sortByDate($a, $b) { if ($a[3] == $b[3]) { return 0; } return ($a[3] < $b[3]) ? -1 : 1; } usort($theArray, 'sortByDate'); ?> EDIT: Or you can make it a one liner like so <?php function sortByDate($a, $b) { return ($a[3] == $b[3])?0:(($a[3] < $b[3]) ? -1 : 1); } ?> Quote Link to comment Share on other sites More sharing options...
Barand Posted August 14, 2008 Share Posted August 14, 2008 It doesn't have to be -1,0,+1; any neg, 0 or pos will suffice, so the custom function can be simplified to function sortByDate($a, $b) { return ($a[3] - $b[3]) ; // swap a, b for DESC sort } Quote Link to comment 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.