perplexing sorting problem

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
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

perplexing sorting problem

Post by titaniumdoughnut »

Hiya folks.

I've got a sorting problem that is beyond the ability of my mortal brain to figure out.

I have an array (called $result) which has an associative array inside each index number (these vary in number, starting at 0 and counting up to an unknown amount). So $result[0] is an associative array, so is $result[1]. Now, each associative array has a number of key-value pairs - always the same keys, differing values.

What I need to do is sort the out-layer array, using alphanumeric order, but sorting based on one of the values inside the associative array contained inside the indexes of the main array. I need to sort $result based on $result[n]["rank"].

Now, if that's possible, I have one more layer of complexity. I need to sort $result based on $result[n]["rank"] and sort within those groupings (many ranks will be the same) based on alphanumeric order within $result[n]["id"]

I KNOW this must be possible... but I fear I've met my match. :?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Code: Select all

function itemsort($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;
}
Call with...

Code: Select all

$SortedArray = itemsort($Array,"SortBy");
Should be a good start.
User avatar
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

Post by titaniumdoughnut »

That's amazing. I barely comprehend it (at first I thought it was pseudocode) but it works perfectly. I call it twice, first to sort by id and then to sort by rank, and it works perfectly. Thanks so much! I'm going to study it, until I understand.
Post Reply