按天将日期数组拆分为不同的数组

时间:2013-01-08 16:26:01

标签: php

我有一个星期的数组,其时间戳如下2013-01-07 06:55:34我想要做的是将数组分割成7个不同的数组。这可能在PHP吗?

我如何创建数组就像这样

$sqlCount="SELECT time_stamp FROM `download_log` WHERE WEEK(`time_stamp`) = WEEK(CURRENT_TIMESTAMP) AND YEAR(`time_stamp`) = YEAR(CURRENT_TIMESTAMP)";
$queryCount = mysql_query($sqlCount) or die(mysql_error());


$dates = array();

while(($row =  mysql_fetch_assoc($queryCount))) {
    $dates[] = $row['time_stamp'];
}

我想要的是7个不同的数组,例如$monday $tuesday etc.,每个数组都有$dates数组中的日期

3 个答案:

答案 0 :(得分:3)

这可以通过PHP date()函数和一些循环操作轻松完成。

以下内容可以帮助您:

// array to hold all of the dates in
$dates = array('Mon' => array(), 'Tue' => array(), 'Wed' => array(),
               'Thu' => array(), 'Fri' => array(), 'Sat' => array(),
               'Sun' => array());

while(($row =  mysql_fetch_assoc($queryCount))) {
    // get the day of the week for the current element
    $dayOfWeek = date('D', $row['time_stamp']);

    // add the current element to the correct day-entry in the `$dates` array
    $dates[$dayOfWeek][] = $row;
}

这是一个示例模板,可以调整使用您喜欢的任何索引(缩写周名,完整的周名,数字星期等)。查看date()功能中的可用值,并根据您的需求进行调整,以便更好地进行调整。

修改
我已经自定义了上面的原始/通用for - 循环以适合您从数据库中读取的while循环。

答案 1 :(得分:1)

我不确定我是否对自己想要的东西非常清楚,但我发现这就是我正在做的事情

$mon = array();
$tue = array();
$wed = array();
$thur = array();
$fri = array();
$sat = array();
$sun = array();

foreach ($dates as $value) {

if(date('D', strtotime($value)) == 'Mon') {
    $mon[] = $value;
    }
    if(date('D', strtotime($value)) == 'Tue') {
    $tue[] = $value;
    }
    if(date('D', strtotime($value)) == 'Wed') {
    $wed[] = $value;
    }
    if(date('D', strtotime($value)) == 'Thu') {
    $thur[] = $value;
    }
    if(date('D', strtotime($value)) == 'Fri') {
    $fri[] = $value;
    }
    if(date('D', strtotime($value)) == 'Sat') {
    $sat[] = $value;
    }
    if(date('D', strtotime($value)) == 'Sun') {
    $sun[] = $value;
    }

}

答案 2 :(得分:0)

为什么不在MySQL中使用内置的WEEKDAY()函数?

$sqlCount = "SELECT WEEKDAY(`time_stamp`) AS 'weekday', `time_stamp` ...";

然后您可以按日期

$dates[$row['weekday']][] = $row['time_stamp'];

另一种选择是内置DATE_FORMAT()功能。使用后(第二个参数)将获得缩写的工作日名称。

$sqlCount = "SELECT DATE_FORMAT(`time_stamp`,'%a') AS 'weekday', `time_stamp` ...";