Sorting a multidimensional 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
lukevrn
Forum Newbie
Posts: 3
Joined: Mon Feb 09, 2009 2:30 pm

Sorting a multidimensional array

Post by lukevrn »

Hi

I have an array whose member consist of arrays. I have a problem sorting them. The problem is that for each index, the array structure may vary but it either has these keys [BookId,BookName,BookSummary,Sort] or [ChapId,ChapName,ChapText,BookId, Sort]. Since Sort is common to both arrays, I want to sort by Sort in descending order. How possible is that?

Thanks
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Sorting a multidimensional array

Post by Weirdan »

http://us2.php.net/array_multisort#func ... t.examples - there's an example called 'sorting database results'. Looks like exactly what you need.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Sorting a multidimensional array

Post by Benjamin »

Code: Select all

 
function sortMultiArrayAsc($items,$key){
    $compare = create_function('$a,$b','
        if ($a["'.$key.'"] == $b["'.$key.'"]) {
            return 0;
        } else {
            return ($a["'.$key.'"] > $b["'.$key.'"]) ? -1 : 1;
        }
    ');
    usort($items,$compare);
    return $items;
}
 
$sorted = sortMultiArrayAsc($items, 'Sort')
 
Post Reply