简体   繁体   中英

How can create a nested array in php dynamically

I want to create a nested array in php. The structure of the array I am trying to create

array(
  'year' => 2017
  'month' => array(
       '0' => 'December',
       '1' => 'December',
   ) 

)

I am trying to create this array dynamically using array_push() function.

$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));
}

This don't work and it shouldn't :). But How can I achieve the structure dynamically.

Thank you.

Initialize the array with the keys you want, and initialize the month element with an empty array. Then fill them in in the loop.

$date = array('year' => null, 'month' => array());
foreach ($allPosts as $p) {
    $date['year'] = date("Y", strtotime($p['published']));
    $date['month'][] = date("F", strtotime($p['published']));
}

The final result will have the year of the last post, and an array of all the months.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM