繁体   English   中英

按日期排序PHP数组表

[英]Sort a PHP Array table by date

我有一个由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]是包含$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 .....文本2 ................日期

1 ........ 75 ............. .......... TOTO 58 ...........塔塔... .... 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


谢谢!

您可以使用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;

输出:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM