2

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'])
                 ); 

Could you help me please?

2 Answers 2

7

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',
  ),
)
Sign up to request clarification or add additional context in comments.

Comments

1
$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

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.