-1

I've got a multidimensional array that stores the location and date of gigs that looks something like this

for ($i=0; $i < $numberOfGigs ; $i++) { 
  $gig[$i] = array(
    "date" => $date,
    "place" => $location
  );
}

I'm getting the date and location from the Google Calendar API and then building a table using the data, however the API's response lists the events in the date they were added to the calendar, rather than the date of the event. This gives me a table looking something like this.

15/03/2014 - Venue 1

30/03/2014 - Venue 2

06/04/2014 - Venue 3

16/03/2014 - Venue 4

I obviously want the events in the table to be sorted chronologically, so I'm looking for a way to sort my $gig array so that $gig[0] is the earliest date and $gig[5] is the latest. I've been looking into sorting arrays, however I'm having trouble getting my head around this multidimensional example.

If anyone could point me in the right direction that would be greatly appreciated!

joshfarrant
  • 1,089
  • 1
  • 14
  • 27

1 Answers1

1

If you have no control about how the array is created, I would suggest to use usort():

$gigs = array(
    array('date' => '15/03/2014', 'place' => 'Venue 1'),
    array('date' => '30/03/2014', 'place' => 'Venue 2'),
    array('date' => '06/04/2014', 'place' => 'Venue 3'),
    array('date' => '16/03/2014', 'place' => 'Venue 4')
);

usort($gigs, 'sortGigs');

print_r($gigs);

function sortGigs($a, $b) {

    $dateA = date_create_from_format('d/m/Y', $a['date']);
    $dateB = date_create_from_format('d/m/Y', $b['date']);
    return date_format($dateA, 'U') > date_format($dateB, 'U');
}

However, if you build the array yourself, convert the date to a timestamp and use it as the key of the array. Then, just use ksort().

$gigs = array();
for ($i=0; $i < $numberOfGigs ; $i++) {
  $date = date_create_from_format('d/m/Y', $date);
  $gigs[date_format($date, 'U')] = $location
}
ksort($gigs);

Loop through the gigs:

$content = '<table>';
foreach($gigs as $timestamp => $place) {
    $content .= '
        <tr>
            <td>' . date('d.m.Y H:i', $timestamp) . '</td>
            <td>' . $place . '</td>
        </tr>
    ';
}
$content .= '</table>';
print $content;
t.h3ads
  • 1,858
  • 9
  • 17
  • Great idea, hadn't even crossed my mind to use the timestamp as the key. I do build the array myself so that's a great solution, my only concern is that won't using the timestamp as a key make it more awkward to access? I was planning on using an incrementing 'for' loop to generate the table in exactly the same way as I did on line 1 in my original post. – joshfarrant Mar 24 '14 at 18:24
  • If you use the timestamp as the key, you can use a `foreach` loop instead of `for`. I will edit my example to show you some code. – t.h3ads Mar 25 '14 at 08:21