Click to See Complete Forum and Search --> : PHP - Sorting Multidimensional Arrays


Robotics Guy
May 1st, 2009, 11:33 AM
This has been driving me NUTS for two days now. How to efficiently sort a multidimensional array by any column.

For example, say I have this multidimensional array (arrays withing an array):

Array
(
[0] => Array
(
[0] => 1
[1] => 20
[2] => hello
)

[1] => Array
(
[0] => 2
[1] => 1
[2] => hi
)

[2] => Array
(
[0] => 3
[1] => 100
[2] => good evening
)

[3] => Array
(
[0] => 4
[1] => 5
[2] => good morning
)
)


This data would actually be stored in a mysql database, and this is the format the array is in when I pull the data.

The first value in each array is the index, the second value is what I want to sort the array's by, and the third is just some textual information.

How would I sort the array so that it would become:

Array
(
[0] => Array
(
[0] => 2
[1] => 1
[2] => hi
)

[1] => Array
(
[0] => 4
[1] => 5
[2] => good morning
)

[2] => Array
(
[0] => 1
[1] => 20
[2] => hello
)

[3] => Array
(
[0] => 3
[1] => 100
[2] => good evening
)
)


Thanks for helping! I really haven't learned about sorting algorithms and appreciate it!

PeejAvery
May 1st, 2009, 02:58 PM
If the data is generated by a database then always sort the data from the database to output into an array. A small example...

SELECT * FROM table ORDER BY column ASC