在PHP中将一些新数据添加到数组中

时间:2010-07-03 15:21:08

标签: php arrays

我有一个像这样的数组:

array('Testing'=>array(
'topic'=>$data['Testing']['topic'], 
'content'=>$data['Testing']'content'])
             ); 

现在我有一些新数据要添加到上面显示的数组中,
我怎么能这样做,以便新的数组看起来像这样:

array('Testing'=>array(
'topic'=>$data['Testing']['topic'], 
'content'=>$data['Testing']['content']),
'new'=>$data['Testing']['new'])
                 ); 

你能帮我吗?

2 个答案:

答案 0 :(得分:7)

与按键访问数组值的方式相同,您也可以按键设置。

<?php
$array = array('foo' => array('bar' => 'baz'));
$array['foo']['spam'] = 'eggs';
var_export($array);

输出:

array (
  'foo' => 
  array (
    'bar' => 'baz',
    'spam' => 'eggs',
  ),
)

答案 1 :(得分:1)

$testing = array(
   'Testing' => array(
      'topic' => 'topic', 
      'content' => 'content'
   )
);

$newTesting = array(
   'Testing' => array(
      'new' => 'new'
   )
);

$testing = array_merge_recursive($testing, $newTesting);

将输出

array (
  'Testing' => array (
    'topic' => 'topic',
    'content' => 'content',
    'new' => 'new',
  ),
)

注意:如果要覆盖某些内容,则使用此方法将无效。例如,如果您有以下内容,则采用相同的初始$testing数组:

$newTesting = array(
   'Testing' => array(
      'content' => 'new content',
      'new' => 'new'
   )
);

$testing = array_merge_recursive($testing, $newTesting);

然后输出将是:

array (
  'Testing' => array (
    'topic' => 'topic',
    'content' => array (
      0 => 'content',
      1 => 'content-override',
    ),
    'new' => 'new',
  ),
)

但如果这是一种理想的行为,那么你就明白了!

编辑:看看这里是否应该替换array_merge_recursive而不是为同一个键添加新元素:http://www.php.net/manual/en/function.array-merge-recursive.php#93905