0

I have this bit of code here and I want to sort the $lessons array by the 'available' field. The array itself contains the lesson ID and the time when the due to start in epoch. I want to sort the time with the first one being the one that is due to start the soonest. I've looked around on the internet but I still don't understand how to use the different sorting functions...

Any help would be great.

    $lessons = array();
    foreach($lessonsArray as $lesson)//for each lesson get the starting time and its lesson id
    {   
        $lessons[] = array( 'id' => $lesson['id'], 'available' => $lesson['available']);            
    }
user1219572
  • 2,326
  • 3
  • 17
  • 13
  • Possible duplicate: http://stackoverflow.com/questions/777597/sorting-an-associative-array-in-php – Josh Feb 29 '12 at 17:51
  • Possible duplicate: http://stackoverflow.com/questions/2382326/how-to-sort-an-array-based-on-a-specific-field-in-the-array – trutheality Feb 29 '12 at 17:52

1 Answers1

0

Try 'uasort()' which receives a callback function as its second parameter. Create the callback function to compare two element arrays in the way you want,

function lessonCompare($a, $b) {
    if ($a['available'] == $b['available']) {
        return 0;
    }
    return ($a['available'] < $b['available']) ? -1 : 1;
}

then call

uasort($lessons, 'lessonCompare');
Umbrella
  • 4,733
  • 2
  • 22
  • 31