Shaun_b Posted February 23, 2009 Share Posted February 23, 2009 Hi I have a multidimensional (2D) array which looks like this: $publications = [ [Title1, 2001, Link1], [Title2, 2008, Link2], [Title3, 2004, Link3], ... etc ] What i would like to do is sort the nested arrays by year desending, like the following, keeping all the other values in the nested array associated with eachother. $publications = [ [Title2, 2008, Link2], [Title3, 2004, Link3], [Title1, 2001, Link1], ... etc ] Im rather new to PHP and all the stuff about sorting arrays is a bit overwhelming at the moment. Thanks for any help. Regards, Shaun Link to comment https://forums.phpfreaks.com/topic/146605-solved-sorting-a-nested-array-in-php/ Share on other sites More sharing options...
trq Posted February 23, 2009 Share Posted February 23, 2009 How is this array being created? If its created via a db query its likely better to do your sort there. Link to comment https://forums.phpfreaks.com/topic/146605-solved-sorting-a-nested-array-in-php/#findComment-769644 Share on other sites More sharing options...
Shaun_b Posted February 24, 2009 Author Share Posted February 24, 2009 It's created from data extracted from an XML file. Link to comment https://forums.phpfreaks.com/topic/146605-solved-sorting-a-nested-array-in-php/#findComment-769649 Share on other sites More sharing options...
Shaun_b Posted February 24, 2009 Author Share Posted February 24, 2009 All good, just found a solution to it: usort($publications, "cmp"); function cmp($a, $b) { return ($b[Year] - $a[Year]); } This will sort the $publications array by the Year value descending. (Note that 'Year' is the named index of the year value). Regards Shaun. Link to comment https://forums.phpfreaks.com/topic/146605-solved-sorting-a-nested-array-in-php/#findComment-769737 Share on other sites More sharing options...
corbin Posted February 24, 2009 Share Posted February 24, 2009 You should enclose index names in quotes (or single quotes) unless you actually mean for them to be a constant. Link to comment https://forums.phpfreaks.com/topic/146605-solved-sorting-a-nested-array-in-php/#findComment-769740 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.