Sorting an array of arrays

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
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Sorting an array of arrays

Post by iankent »

This is possibly a silly question, but I dont seem to be able to get it to work. I'm trying to sort an array of arrays that looks much like this:

Code: Select all

$arr = array(
    1    =>    array(
        'title'    =>    'something',
        'id'       =>    '1952378',
    ),
    2    =>    array(
        'title'    =>    'blah blah blah',
        'id'       =>    '3427682',
    ),
    10    =>  array(
        'title'    =>    'something else',
        'id'       =>    '9827324',
    ),
);
 
If I then add another element to the array, like this:

Code: Select all

$arr[5] = array(
    'title'    =>    'new entry',
    'id'       =>    '1234567',
);
 
I end up with an array whose elements are numbered 1, 2, 10, 5. I'd like to reorder that so its 1, 2, 5, 10. I've tried using sort and asort with no luck, whatever I try and do it orders the arrays by the contents of 'title' and not by the number they're assigned. It doesn't matter if the number assigned (1, 2, 5, 10) is lost during the sort, just as long as it sorts by those and not by elements inside the arrays.

Thanks :)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Sorting an array of arrays

Post by pickle »

Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Sorting an array of arrays

Post by iankent »

lol, seems so obvious now! thanks :)
Post Reply