如何动态地在php中创建嵌套数组

问题描述 投票:0回答:1

我想在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));
}

这不起作用,它不应该:)。但是我如何动态地实现结构。

谢谢。

php arrays
1个回答
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']));
}

最终结果将包含最后一篇文章的年份,以及所有月份的数组。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.