这是我想要的结果:
January 2018
Division A
Division B
Division C
February 2018
Division A
Division B
Division C
..so on..
在控制器中,这是代码:
$i = 0;
for ($dd = $start_date; $dd <= $last_date;) {
$month_iteration = date("F Y",strtotime($dd));
$data['months'][$i] = $month_iteration; // this successfully saves months in months array
$dd = date('Y-m-d', strtotime($dd . 'next month')); // ctr++
$i++;
}
foreach ($data['months'] as $m_key) { // for every month saved, I need to print all divisions
$data['months'][$m_key]['divisions'] = $this->division_model->get_divisions();
}
通常,当我在foreach内部使用foreach时,它可以正常工作。在这种情况下,除了使用for循环外,我不确定如何在数组中保存几个月。
使用上面的代码,结果是:
January 2018
error Invalid argument supplied for foreach()
February 2018
error Invalid argument supplied for foreach()
Array
Division A Division B Division C
Array
Division A Division B Division C
因此它分别打印月份和除法并乘以(?)
我尝试使用以下代码将除法保存在for循环中:
$data['months'][$i]['divisions'] = $this->division_model->get_divisions();
当我执行var_dump($data)
时,除法没有显示任何内容。我了解使用这种方法也是错误的。
我做错了什么?达到所需结果的最佳方法是什么?
答案 0 :(得分:0)
我认为这会对您有所帮助。
$weeks['start_date'] = '2018/01/01';
$weeks['end_date'] = '2018/08/01';
$daterange = new DatePeriod(new DateTime($weeks['start_date']), new DateInterval('P1M'), new DateTime($weeks['end_date']));
$weekDayList = array();
foreach ($daterange as $date) {
$weekDayList[$date->format("F Y")]['divisions'] = ['division1','division2','division3'];
}
echo "<pre>";
print_r($weekDayList);
如果这是您要寻找的 结果::
Array
(
[January 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[February 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[March 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[April 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[May 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[June 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
[July 2018] => Array
(
[divisions] => Array
(
[0] => division1
[1] => division2
[2] => division3
)
)
)