Page 1 of 1

Sorting a multidimensional array

Posted: Mon Feb 09, 2009 2:34 pm
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

Re: Sorting a multidimensional array

Posted: Mon Feb 09, 2009 2:42 pm
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.

Re: Sorting a multidimensional array

Posted: Mon Feb 09, 2009 3:20 pm
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')