Jump to content

PHP Sort Multi Dimension array

dirtbikerxz
Go to solution Solved by fizzlesticks,

Use usort

The first parameter is the array and the second parameter is a function that takes 2 arguments which are the 2 values being compared (arrays in your case.)

The function needs to return 0 if 2 objects are equal, 1 if the first parameter is greater and -1 if the first parameter is less. If you're using PHP 7 the function will look something like:

usort($your_array, function($a, $b) { return $a[1] <=> $b[1]; });

 

I have a multidimensional array like so:

events[0][0] = txho

events[0][1] =  2016-04-27

events[0][2] = CMP

 

events[1][0] = ONTA

events[1][1] =  2016-04-12

events[1][2] = CMP1

 

events[2][0] = LAKE

events[2][1] =  2016-07-13

events[2][2] = MER

 

how do I get php to sort the array using the date portion of each array essentially (events[x][1])

so that the array becomes

 

events[0][0] = ONTA

...etc (remaining two fields)

 

events[1][0] = txho

...etc (remaining two fields)

events[2][0] = LAKE

...etc (remaining two fields)

 

thanks in advance

Link to comment
Share on other sites

Link to post
Share on other sites

Use usort

The first parameter is the array and the second parameter is a function that takes 2 arguments which are the 2 values being compared (arrays in your case.)

The function needs to return 0 if 2 objects are equal, 1 if the first parameter is greater and -1 if the first parameter is less. If you're using PHP 7 the function will look something like:

usort($your_array, function($a, $b) { return $a[1] <=> $b[1]; });

 

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×