如何在多维关联数组上存储日期?

时间:2015-08-14 03:03:05

标签: php arrays date multidimensional-array

如何在多维关联数组上存储日期? 我无法进一步解释我的问题,但如果我有一个包含不同日期的数组怎么办?例如:

<?php 
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
?>

我想根据他们的月份将上面的数组存储到多维关联数组中,所以它就像这样..

<?php
array = array(
"June" => array("2015-06-01","2015-06-07"),
"July"=> array("2015-07-08"),
"August" => array("2015-08-01","2015-08-21","2015-08-26")
);

?>

但是在我的情况下,日期来自数据库与上面定义日期的示例比较,如何根据月份对以下日期进行分组,并存储在根据其月份命名的关联数组中,内容为包含日期分组的第二维数组?

谢谢!

我上面的代码只是示例:这是我的解决方案,但它不能正常工作! -_-

<?php 
include($_SERVER["DOCUMENT_ROOT"] . "/empc/library/functions.php");
$previousmonth = "";
$a = getDistinctDates(); // Function that get dates, nevermind of this.
$data = array();
foreach ($a as $b){ 
    echo $b["date_modified"] . "<br>";
    $datemonth = date("F",strtotime($b["date_modified"]));
    echo $datemonth . "<br>";

    if ($datemonth != $previousmonth){
        array_push($data,
            array(
                $datemonth => $b["date_modified"]
            )
        );
    } else {
        array_push($data[$datemonth][],$b["date_modified"]);
    }

    echo $b["balance_after_approval"] . "<br>";
    echo "<br>";
    $previousmonth = $datemonth;
}
?>

1 个答案:

答案 0 :(得分:1)

你在想这个,只需使用月份作为数组键:

<?php 
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
$out=array();
foreach ($dates as $b){ 
    $datemonth = date("F",strtotime($b));
    $out[$datemonth][]=$b;
}
  print_r($out);

?>

演示:http://codepad.viper-7.com/3Gh9s7