0

Possible Duplicate:
How do I sort a multidimensional array in php
Sorting a multidimensional array in PHP?

How can I sort an array (see below) by high, medium, low?

# Generate random events
$severity = array('high','medium','low');
$events = array();
for ($i=1,$n=10;$i<=$n;$i++) {
        $events["Country{$i}"] = array(
                'high'          =>              rand(0,100),
                'medium'        =>              rand(0,100),
                'low'           =>              rand(0,100),
                'total'         =>              'X'
        );
}

I means that in the bottom line i'll have a sorted array which holds all the countryX sorted by the highest value of high, then medium, and then low - all in 1 big array.

tried different approaches but faild to get the correct result.

Community
  • 1
  • 1
Broshi
  • 2,593
  • 4
  • 29
  • 47

1 Answers1

0
function sillySort($a, $b) {
    if ($a['high'] > $b['high']) {
         return -1;
    } else if ($a['high'] < $b['high']) {
         return 1;
    } else {
        if ($a['medium'] > $b['medium']) {
            return -1;
        } else if ($a['medium'] < $b['medium']) {
            return 1;
        } else {
            if ($a['low'] > $b['low']) {
                return -1;
            } else if ($a['low'] < $b['low']) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}

uksort($events, 'sillySort');
Ingmar Boddington
  • 3,200
  • 16
  • 35