0

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.

9
  • You don't use array_push() to create associative arrays. Commented Dec 21, 2017 at 22:45
  • Got it. Then index will work? Let me try :) thanks Commented Dec 21, 2017 at 22:46
  • I don't really understand what you're trying to do. You have a loop in your code, but where would you put multiple years in the desired result? Commented Dec 21, 2017 at 22:47
  • I want to put the result in $date array which I am trying to make a nested array Commented Dec 21, 2017 at 22:48
  • 1
    Can you show what $p['published'] looks like? The contents of it or one of them? Commented Dec 21, 2017 at 22:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.