我有一个由PHP和Array生成的多列HTML表,从包含条目列表的数据库中的表中获取数据。 5列中的一列是日期戳。我希望 HTML表格按时间戳 进行排序,没有任何代码可以按ID(column0)对其进行排序。
以下是我要排序的代码:
$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]
是包含日期戳的那个。我尝试过sort(),asort(),array_multisort()......没有任何运气。
这是SQL表结构:
column0: id
column1: number1
column2: text1
column3: number2
column4: text2
column5: date (format: Y-m-d H:m:s)
以下是其内容的示例,我需要按列日期排序:
ID ..... .....数字1 text1的..... ..... NUMBER2 ................ text2的日期
1 ........ 75 .............托托.......... 58 ...........塔塔....... 2014-04-07 16:43:51 2 ........ 34 .............短裙.......... 07 ...........蒂蒂... ...... 2013-04-09 08:27:34 3 ........ 83 ............. tyty .......... 53 ...........面对面... .... 2015-04-08 12:36:18
谢谢!
答案 0 :(得分:3)
您可以使用usort()
并按strtotime()
比较日期。这里有一个例子..
$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 as $key){
$html .= '<th>'.$key.'</th>';
}
$html .= '</tr>';
foreach($arr as $value){
$html .= '<tr>';
foreach($value as $val){
$html .= '<td>'.$val.'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
<强>输出:强>