Sorting MultiDimensional Arrays? Based on sorting 1 array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
imsoconfused
Forum Newbie
Posts: 15
Joined: Mon Oct 05, 2009 10:55 pm

Sorting MultiDimensional Arrays? Based on sorting 1 array

Post by imsoconfused »

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


I have a multidimensional array (2D) that i am trying to sort..

Code: Select all

$blackhole = array(
         'idNumber'=>array(),
         'title'=>array()
                  );
is there a way to sort array idNumber and then based on the changes made in that array apply it to the other arrays? example

///////UNSORTED
$blackhole idNumber = 2 4 1 3 5
$blackhole title = 'Had' 'Little' 'Mary' 'A' 'Lamb'

//////SORTED
$blackhole idNumber = 1 2 3 4 5
$blackhole title = Mary Had A Little Lamb


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Sorting MultiDimensional Arrays? Based on sorting 1 array

Post by pickle »

You're looking for array_multisort(). It's a bit of a beast, so I'll give you an idea how to use it. Basically you want to pull apart $blackhole into your 'idNumber' and 'title' arrays. You can then use array_multisort() to sort idNumber, then apply the re-ordering to the 'title' array.

Something like (untested & probably wrong):

Code: Select all

$ids = $blackhole['idNumber'];
$titles = $blackhole['titles'];
 
array_multisort($ids,SORT_ASC,$titles);
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply