2010-07-03 112 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

相關問題