Jump to content

[SOLVED] Sorting a nested array in PHP


Shaun_b

Recommended Posts

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

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.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.