按日期对PHP数组表进行排序 [英] Sort a PHP Array table by date

查看:159
本文介绍了按日期对PHP数组表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP用Array生成的多列HTML表,从包含条目列表的数据库中的表中获取数据. 5列之一是日期戳.我希望 HTML表按时间戳排序 ,而没有任何代码按ID(column0)对其进行排序.

I have a multi-columns HTML table generated by PHP with Array, taking data from a table in a database which contains a list of entries. One of the 5 columns is a datestamp. I would like the HTML table to be sorted by timestamp, without any code it sorts it by ID (column0).

这是我必须排序的代码:

Here is the code I have to 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]是包含日期戳的那个.我尝试过sort(),asort(),array_multisort()...没有任何运气.

$column5[$i][5] is the one containing the datestamp. I've tried sort(), asort(), array_multisort()... without any luck.

这是SQL表结构:

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

这是其内容的示例,我需要按日期列对其进行排序:

And here is an example of its content, for which I need to sort by the column date:

id ..... number1 ..... text1 ..... number2 ..... text2 ....... 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

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

谢谢!

推荐答案

您可以使用usort()并按strtotime()比较日期.一个例子.

You can use usort() and compare date by strtotime(). An 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 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;


输出:

这篇关于按日期对PHP数组表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆