我有一个按月分组的多维元素数组,例如:
Array
(
[2013-01] => Array
(
[0] => Array
(
[Project] => Array
(
[id] => 1
[user_id] => 1
[created] => 2013-04-08 01:00:56
[modified] => 2013-04-08 01:01:40
[vId] => 7
)
)
)
[2013-04] => Array
(
[2] => Array
(
[Project] => Array
(
[id] => 1
[user_id] => 1
[created] => 2013-04-08 01:00:56
[modified] => 2013-04-08 01:01:40
[refimg] => uploads/smallRef.png
)
)
[3] => Array
(
[Project] => Array
(
[id] => 1
[user_id] => 1
[created] => 2013-04-08 01:00:56
[modified] => 2013-04-08 01:01:40
)
)
[4] => Array
(
[Project] => Array
(
[id] => 1
[user_id] => 1
[created] => 2013-04-08 01:00:56
[modified] => 2013-04-08 01:01:40
)
)
)
)
现在我想循环几个月,并且每个月我想对特定月份的数组执行计数:
$currMonth = date('Y-m-d');
while (strtotime($currMonth) >= strtotime($firstMonth)) {
$curM = date('Y-m', strtotime($currMonth));
count($grouparr[$curM]);
$currMonth = date ("Y-m-d", strtotime("-1 month", strtotime($currMonth)));
}
这似乎不起作用。我收到以下错误:
Uncaught SyntaxError: Unexpected token <
如果我手动输入日期,一切正常,例如,如果我在上面的代码中替换它:
count($grouparr["2013-01");
我希望有人可以告诉我我做错了什么
答案 0 :(得分:0)
foreach($yourarray as $month) {
echo sizeof($month);
}
答案 1 :(得分:0)
foreach ($grouparr as $month => $values) {
echo "$month: " . count($values) . "<br />";
}
答案 2 :(得分:0)
恕我直言,如果你能提供帮助,请不要使用strtotime()函数。我不确切知道你的最终结果是什么,但是在迭代这样的数组时让我提供几个选择。
首先,如果您只想循环遍历数组......
foreach ($grouparr as $key => $val) {
list($year, $month) = explode("-", $key, 2);
printf("%s, %s has %s records",
$month,
$year,
is_array($val) ? count($val) : 0
);
}
或许你想要过去12个月......
for ($i = 1; $i <= 12; $i++) {
//Use this timestamp for all your date calculations
$mytime = mktime(0, 0, 0, date("n") - $i, 1, date("Y"));
if (array_key_exists( date("Y-m", $mytime), $grouparr)) {
printf("%s, %s has %s records",
date("F", $mytime),
date("Y", $mytime),
is_array($grouparr[date("Y-m", $mytime)]) ? count(date("Y-m", $mytime)) : 0
);
}
}
这些代码示例可以更简单,但是......