How to add elements to an array

Asked

Viewed 348 times

1

Come on guys, I’m sure it’s a very simple question, but I can’t do it.

First scenario - I have the following array:

$century = array(
    'decade' => array(
        array(
            'year' => '2017',
            'months' => array(
                array('value' => 'Jan'),
            )
        )
    )
);

echo "<pre>";
print_r(json_encode($century));
echo "</pre>";

{"Issue":[{"year":"2017","months":[{"value":"Jan"}]}]}

So far so good, the format is as desired, but changing the way I create this array and assign values, tb changes the output to an unwanted format, see below.


Second Scenario - Unwanted Format:

$m = array(
    array('value' => 'Jan')
);

$century = array(
    'decade' => array()
);

$century['decade'][]['year'] = '2017';
$century['decade'][]['months'] = $m[0]['value'];


echo "<pre>";
print_r(json_encode($century));
echo "</pre>";

{"Issue":[{"year":"2017"},{"months":"Jan"}]}

Note that now the "year" is involved by '{}' individually and not as a whole as in the first scenario.

The point is, obviously there’s a certain way to make the second scenario to return an output equal to the first, but which?

1 answer

3

Such behaviour is due to the use of the operator [] in its variable $century['decade']. Whenever you use this operator, PHP will create a new element in the array in question, i.e., do:

$century['decade'][]['year'] = '2017';
$century['decade'][]['months'] = $m[0]['value'];

Create a new element by adding the year and create a new element when adding the months. That’s why its output has two elements instead of one, as expected.

To get around this simply, just create the array before making the assignments, as shown below:

$m = array(
    array('value' => 'Jan')
);

$century = array(
    'decade' => array()
);

// Aqui é criado um array único, atribuindo corretamente os valores:
$array = array(
    'year' => '2017',
    'months' =>  $m[0]['value']
);

// Insere o novo array na variável $century['decade']:
$century['decade'][] = $array;

print_r(json_encode($century)); 

See the code working on Ideone.

  • I tried to rewrite his answer in a clearer way. In my view, there was a lot of repetition in a paragraph, which made it difficult to read. If you feel you’re not living up to your answer, feel free to do the rollback edition. I took advantage and added your example in Ideone. I hope you don’t mind.

  • Thanks for the answer and I understood your explanation, but what if I need to iterate over the array the other months, example: (February, March, April.. etc)?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.