tags:

views:

33

answers:

1

Hi

For the last couple of days i tried to get my head around the following:

I have a 2-dimensional Array and i try to sort it with a custom algorithm using usort().

My Problem is, that I'm trying to sort numbers like in the order of 1 2 3 0 so the zero should always be the last item.

function customsort($e1, $e2) {
    if ($e1["number"] == $e2["number"]) {
        return $e1["year"] - $e2["year"];
    } elseif ($e1["number"] == 0) {
        return 1;
    } else {
        return $e1["number"] - $e2["number"];
    }
}

I thought this would do the trick but only a part of the entrys with a zero got sorted to the end of the list. I'm pretty shure, that the list is not corrupt and dumping the whole array shows me, that every used entry delivers a zero where it should be, but they are not sorted the right way.

Thanks in advance, Johnny

+2  A: 

You forgot to apply the same reasoning to e2:

function customsort($e1, $e2) {
    if ($e1["number"] == $e2["number"]) {
        return $e1["year"] - $e2["year"];
    } elseif ($e1["number"] == 0) {
        return 1;
    } elseif ($e2["number"] == 0) {
        return -1;
    } else {
        return $e1["number"] - $e2["number"];
    }
}

You're compare function must have this property to make sense

customsort($foo, $bar) == -1*customsort($bar, $foo)

for every $foo and $bar. In particular (what went wrong in your case)

customsort({'number'=>3},{'number'=>0}); // should give a negative number, because
customsort({'number'=>0},{'number'=>3}); // gives a positive number
Ishtar
Thank you very much
Johnnycube
@Johnnycube - You're welcome
Ishtar