【发布时间】:2017-07-12 15:36:12
【问题描述】:
我有列 date_added,它的格式日期为 2017-02-09 08:45:48。我想将同一月份的所有记录存储在该特定月份内,例如二月记录应该在二月数组内。我正在尝试以下代码。
$Res = array();
$query = $this->pdoConnection->prepare("select id,date from `record` ");
$query->execute();
header("Content-type: application/json; charset=utf-8");
$month = array(1,2,3,4,5,6,7,8,9,10,11,12);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$Data = $row;
$array_date = date("m", strtotime($row['date']));
$alpha_month = date("M", strtotime($row['date']));
if(in_array($array_date,$month)){
$Res[] = array($alpha_month=>array($Data));
}
}
$output = array(
'response' => $Res
);
echo json_encode($output,JSON_PRETTY_PRINT);
结果
{
"response": [
{
"Jan": [
{
"id": "1",
"date_added": "2017-01-03 08:43:09"
}
]
},
{
"Feb": [
{
"id": "4",
"date_added": "2017-02-04 10:53:44"
}
]
},
{
"Feb": [
{
"id": "2",
"date_added": "2017-02-12 08:59:15"
}
]
}
]
}
如您所见,我的代码返回单独的二月数组,但我想将两者都存储在二月数组中。我尝试了不同的逻辑,但仍然面临同样的问题。
【问题讨论】:
-
你可以改为
$Res[] = array($alpha_month=>array($Data));$Res[$alpha_month][] = $Data; -
@Tyralcori 您为我提供了非常快速的解决方案和指导 +1。但由于要点较少,我无法对您的评论投赞成票
-
我在“答案”中对所有内容进行了更详细的解释。我很高兴我能提供帮助。如果您需要更多信息,请随时联系。