我有一个PHP用Array生成的多列HTML表,从包含条目列表的数据库中的表中获取数据。5列之一是日期戳。我希望HTML表按timestamp排序,而没有任何代码按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 ..... number1 ..... text1 ..... number2 ..... text2 ....... date
1 ... 75 ........ toto ................... 58 ...... tata ... .... 2014-04-07 16:43:51 2 ........ 34 ......................芭蕾舞短裙.......... 07。 .......... titi ......... 2013-04-09 08:27:34 3 ........ 83 ..... ... tyty ................... 53 ........... tete ....... 2015-04-08 12:36:18
谢谢!
您可以按来使用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;
输出:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句