Page 1 of 1

perplexing sorting problem

Posted: Tue May 23, 2006 10:56 pm
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. :?

Posted: Tue May 23, 2006 11:37 pm
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.

Posted: Wed May 24, 2006 1:06 pm
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.