我想在php中创建一个嵌套数组。 我正在尝试创建的数组的结构
array(
'year' => 2017
'month' => array(
'0' => 'December',
'1' => 'December',
)
)
我正在尝试使用array_push()函数动态创建此数组。
$date=array();
foreach ($allPosts as $p) {
$year=date("Y", strtotime($p['published']));
$month=date("F", strtotime($p['published']));
array_push($date, $year);
array_push($date['month'], array($month));
}
这不起作用,它不应该:)。但是我如何动态地实现结构。
谢谢。
答案 0 :(得分:1)
使用所需的键初始化数组,并使用空数组初始化month
元素。然后将它们填入循环中。
$date = array('year' => null, 'month' => array());
foreach ($allPosts as $p) {
$date['year'] = date("Y", strtotime($p['published']));
$date['month'][] = date("F", strtotime($p['published']));
}
最终结果将包含最后一篇文章的年份,以及所有月份的数组。