2010-07-03 111 views
2

我有一个这样的数组:添加一些新的数据到一个数组中的PHP

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

现在我已经得到了一些新的数据添加到显示aboved阵列,
我怎么能做到这一点,使新阵列将如下所示:

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

请问您能帮助我吗?

回答

7

就像你可以通过键访问数组值一样,你也可以通过键设置。

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

输出:

array (
    'foo' => 
    array (
    'bar' => 'baz', 
    'spam' => 'eggs', 
), 
) 
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

相关问题