Reputation: 3209
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.
Upvotes: 0
Views: 352
Reputation: 781058
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.
Upvotes: 1