Add some new data into an Array in PHP
I got an Array like this:
array('Testing'=>array(
'topic'=>$data['Testing']['topic'],
'content'=>$data['Testing']'content'])
);
Now I have got some new data to add into the Array shown aboved,
how can I do it so that the new Array will look like this:array('Testing'=>array(
'topic'=>$data['Testing']['topic'],
'content'=>$data['Testing']['content']),
'new'=>$data['Testing']['new'])
);开发者_如何学Go
Could you help me please?
In the same way that you can access arrays values by key, you can set by key, as well.
<?php
$array = array('foo' => array('bar' => 'baz'));
$array['foo']['spam'] = 'eggs';
var_export($array);
Output:
array (
'foo' =>
array (
'bar' => 'baz',
'spam' => 'eggs',
),
)
$testing = array(
'Testing' => array(
'topic' => 'topic',
'content' => 'content'
)
);
$newTesting = array(
'Testing' => array(
'new' => 'new'
)
);
$testing = array_merge_recursive($testing, $newTesting);
will output
array (
'Testing' => array (
'topic' => 'topic',
'content' => 'content',
'new' => 'new',
),
)
NOTE : if you want to override something, using this method will not work. For example, taking the same initial $testing
array, if you have :
$newTesting = array(
'Testing' => array(
'content' => 'new content',
'new' => 'new'
)
);
$testing = array_merge_recursive($testing, $newTesting);
Then the output will be :
array (
'Testing' => array (
'topic' => 'topic',
'content' => array (
0 => 'content',
1 => 'content-override',
),
'new' => 'new',
),
)
But if this is a desired behavior, then you got it!
EDIT : take a look here to if array_merge_recursive should replace instead of adding new elements for the same key : http://www.php.net/manual/en/function.array-merge-recursive.php#93905
精彩评论