Adding elements to an array

1

Personally, I'm sure it's a very simple question, but I'm not sure how to 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>";
  

{"decade": [{"year": "2017", "months"

So far so good, the format is like wish, but changing how I create this array and assigns 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>";
  

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

Notice that the year is now surrounded by '{}' individually and not as a whole as in the first scenario.

The question is of course have a right way to do the second scenario to return an output equal to the first, but which?

    
asked by anonymous 08.03.2017 / 15:49

1 answer

3

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

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

Create a new element when you add the year and create a new element when you add the months. So your output has two elements instead of one, as expected.

To get around this in a simple way, simply create the array before doing 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 at Ideone .

    
08.03.2017 / 16:00