Question

I've got an array for events on my site that looks like this:

array(
    'title' => 'Name',
    'link' => 'http://www.eventssite.com',
    'image' => '_img/event_img.jpg',
    'location' => 'Florida, US',
    'year' => '2013',
    'date' => 'Dec. 12-14',
    'desc' => 'Description about the event.',
    'dateid' => '1212013'
),

I'd like to sort the array before the foreach by the dateid so that they show in the proper Date order.

Additionally I'm trying to identify which one of the events is closest to the actual date, as I am using a carousel type system that needs to know which to display first.

I've researched usort and am not able to get it to go on my own, Thank you for any assistance on these!

Was it helpful?

Solution

Using this function: http://php.net/usort

An example would be something like:

<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
    array(
        'date' => '05/02/1988',
        'name' => 'Jacob'
    ),
    array(
        'date' => '12/12/1968',
        'name' => 'Sherry'
    ),
    array(
        'date' => '05/15/1978',
        'name' => 'Dave'
    )
);

//usort is used for non conventional sorting. 
//which could help in this case
//NOTICE - we are not setting a variable here! 
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');

//display the results
var_dump($array);

//function called by usort
function sortFunction($a,$b){
    //turn the dates into integers to compare them
    //
    $strA = strtotime($a['date']);
    $strB = strtotime($b['date']);

    //don't worry about sorting if they are equal
    if($strA == $strB){
        return 0;
    }
    else{
            //if a is smaller than b, the move it up by one.
        return $strA < $strB ? -1 : 1; 
    }
}
?>

(in case youre interested, line 40 is called a Ternary) edited for clarity

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top