views:

112

answers:

3

So Ive got a pretty big array of data and need to sort them by two criteria.

There is variable $data['important'] and $data['basic'].

They are simple numbers and I am using uasort to sort $data firstly by important and then by basic.

So

Important | Basic
10        | 8
9         | 9
9         | 7
7         | 9

The usort function is a simple

public function sort_by_important($a, $b) {

        if ($a[important] > $b[important]) {
            return -1;
        } 
        elseif ($b[important] > $a[important]) {
            return 1;
        } 
        else {
            return 0;
        }
    }

How can I re-sort the array to the second variable and keep the Important ordering?

Thanks everyone.

EDIT

How about adding a third sorting option after this even? So Important > Basic > Less

+1  A: 

Why not simply use array_multisort()

public function sort_by_important($a, $b) { 
    if ($a['Important'] > $b['Important']) { 
        return -1; 
    } elseif ($b['Important'] > $a['Important']) { 
        return 1; 
    } else { 
        if ($a['Basic'] > $b['Basic']) { 
            return -1; 
        } elseif ($b['Basic'] > $a['Basic']) { 
            return 1; 
        } else { 
            return 0; 
        }
    } 
} 
Mark Baker
array_multisort was the right answer, Ive got to give the points to kenny because he gave me the answer on the place, placing the order into seperate variables was the bit that confused me. Thanks for your help!
bluedaniel
+1  A: 

You really should use array_multisort(),

// Obtain a list of columns
foreach ($data as $key => $row) {
    $important[$key]  = $row['important'];
    $basic[$key] = $row['basic'];
}

array_multisort($important, SORT_NUMERIC, SORT_DESC,
                $basic, SORT_NUMERIC, SORT_DESC,
                $data);

but if you must use usort():

public function sort_by_important($a, $b) {

    if ($a[important] > $b[important]) {
        return -1;
    } elseif ($b[important] > $a[important]) {
        return 1;
    } else {
        if ($a[basic] > $b[basic]) {
            return -1;
        } elseif ($b[basic] > $a[basic]) {
            return 1;
        } else {
            return 0;
        }
    }
}
KennyTM
A: 

How about adding a third sorting option after this even? So Important > Basic > Less

I repeat, array_multisort()

Mark Baker
Im giving you an up vote because you were right
bluedaniel