Sorting a multidimensional PHP array chronologically -
this question has answer here:
- how can sort arrays , data in php? 7 answers
i've got multidimensional array stores location , date of gigs looks this
for ($i=0; $i < $numberofgigs ; $i++) { $gig[$i] = array( "date" => $date, "place" => $location ); }
i'm getting date , location google calendar api , building table using data, api's response lists events in date added calendar, rather date of event. gives me table looking this.
15/03/2014 - venue 1
30/03/2014 - venue 2
06/04/2014 - venue 3
16/03/2014 - venue 4
i want events in table sorted chronologically, i'm looking way sort $gig array $gig[0] earliest date , $gig[5] latest. i've been looking sorting arrays, i'm having trouble getting head around multidimensional example.
if point me in right direction appreciated!
if have no control how array created, suggest 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 build array yourself, convert date timestamp , use key of array. then, use ksort().
$gigs = array(); ($i=0; $i < $numberofgigs ; $i++) { $date = date_create_from_format('d/m/y', $date); $gigs[date_format($date, 'u')] = $location } ksort($gigs);
loop through gigs:
$content = '<table>'; foreach($gigs $timestamp => $place) { $content .= ' <tr> <td>' . date('d.m.y h:i', $timestamp) . '</td> <td>' . $place . '</td> </tr> '; } $content .= '</table>'; print $content;
Comments
Post a Comment