0

I'm using array_add($array, 'key', 'value'); to create the data structure.

foreach ($archives as $archive){
    $results = array_add($results, $archive->year, 
              array($archive->month => array('name' => $archive->month_name)));
}

If i json_encode()the $results i get this output:

{ 
   2015: {
       02: {name:'February'}
   }
}

But i want something like:

{
   2015: {
       02: {name:'February'},
       01: {name:'January'}
   }
}

And of course this should works for different years too.

4
  • array_add isn't a core php function, can you show the function aswell? Besides $results is overwritten in every iteration. Commented Feb 10, 2015 at 15:17
  • 1
    Why are you using a (IMHO pointless, and messy-looking) function (array_add), when you could just write $results[$archive->year] = array($archive->month => array('name' => $archive->month_name));? Oh, and could it be that "January" isn't int $results because it's not in the $archives to begin with? check those values, too Commented Feb 10, 2015 at 15:19
  • @EliasVanOotegem with your code i get the same output but with January and not February. Commented Feb 10, 2015 at 15:31
  • @idknow: Because you'd need to check if $results[$archive->year] doesn't already exist, if it does, your code currently reassigns it (overwriting the array that it already holds), I'll post an answer Commented Feb 10, 2015 at 15:33

2 Answers 2

1

In response to my comments - here's what I'd do:

foreach ($archives as $archive)
{
    if (!isset($results[$archive->year]))
    {//if the year-key doesn't exist yet, create it
     //if it already exists, this part will be skipped
        $results[$archive->year] = array();
    }
    //then add the values
    $results[$archive->year][$archive->month] = array(
        'name' => $archive->month_name
    );
}

That's all there is to it, no need for a home-made function or anything like that

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

Comments

0

How about array_push($array, 'key', 'value');

1 Comment

That won't work at all, that'll push 'key' and 'value' as separate values onto $array consecutively see the manual

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.