Sort a PHP Array table by date -


i have multi-columns html table generated php array, taking data table in database contains list of entries. 1 of 5 columns datestamp. the html table sorted by timestamp, without code sorts id (column0).

here code have sort:

$table .= "<tr><td>" . $column0[$i][0] ."</td><td>" . $column1[$i][1] . "</td><td>" . $column2[$i][2] . "</td><td>" . $column3[$i][3] . "</td><td>" . $column4[$i][4] . "</td><td>" . $column5[$i][5] . "</td></tr>"; 

$column5[$i][5] 1 containing datestamp. i've tried sort(), asort(), array_multisort()... without luck.

here sql table structure:

column0: id column1: number1 column2: text1 column3: number2 column4: text2 column5: date (format: y-m-d h:m:s) 

and here example of content, need sort column date:


id.....number1.....text1.....number2.....text2................date

1........75.............toto..........58...........tata.......2014-04-07 16:43:51 2........34.............tutu..........07...........titi.........2013-04-09 08:27:34 3........83.............tyty..........53...........tete.......2015-04-08 12:36:18


thank you!

you can use usort() , compare date strtotime(). example here..

$arr = array(     0 => array('id'=>1,'number1'=>'75','text1'=>'toto','number2'=>'58','text2'=>'tata','date'=>'2014-04-07 16:43:51',),     1 => array('id'=>2,'number1'=>'34','text1'=>'tutu','number2'=>'07','text2'=>'titi','date'=>'2013-04-09 08:27:34',),     2 => array('id'=>3,'number1'=>'83','text1'=>'tyty','number2'=>'53','text2'=>'tete','date'=>'2015-04-08 12:36:18',), );  function sort_by_date($a, $b) {     $a = strtotime($a['date']);     $b = strtotime($b['date']);     if ($a == $b) {         return 0;     }     return ($a < $b) ? -1 : 1; }  usort($arr, 'sort_by_date');  $keys = array_keys(current($arr));  $html = '<table border="1"><tr>'; foreach($keys $key){     $html .= '<th>'.$key.'</th>'; } $html .= '</tr>';  foreach($arr $value){     $html .= '<tr>';     foreach($value $val){         $html .= '<td>'.$val.'</td>';     }     $html .= '</tr>'; } $html .= '</table>'; echo $html; 

output:

enter image description here


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -