2009-08-30 129 views
141

我有一個現有的數組,我想要添加一個值。array_push()與鍵值對

我試圖實現,使用array_push()無濟於事。

下面是我的代碼:

$data = array(
    "dog" => "cat" 
); 

array_push($data['pussy'], 'wagon'); 

我想實現的是作爲重點與貨車添加$data數組值,以訪問它,如下面的代碼片段:

echo $data['pussy']; // the expected output is: wagon 

我該如何做到這一點?

回答

248

那麼,關於有:

$data['pussy']='wagon'; 
+0

如果貓是在一個變量? $ pussy ='pussy'; $ data [$ pussy] ='wagon'; 試試這個,它給了我一個錯誤 – Dynelight 2014-10-05 20:26:55

+0

@Dynelight這不會給我一個錯誤;你得到的錯誤究竟是什麼? – 2017-08-15 16:09:36

+1

感謝您的回答和幽默。 ;-) – 2017-09-07 17:44:58

29
$data['pussy'] = 'wagon'; 

這就是你需要添加鍵和值的數組。

29

如果您需要添加多個key =>值,請嘗試此操作。

$data = array_merge($data, array("pussy"=>"wagon","foo"=>"baar")); 
+0

這不會在數組中添加任何值。 – 2015-11-22 06:19:47

+2

它增加或改變現有的鍵。請RTFM。 – 2015-11-30 09:20:47

2

例如:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue'); 

要想改變密鑰值:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array 

輸出:

陣列([firstKey] => changedValue [secondKey] => secondValue)

對於添加新的密鑰值對:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array 

輸出:

陣列([firstKey] => firstValue [secondKey] => secondValue [則newkey] => newValue)以

-2

只要做到這一點:

$data = [ 
    "dog" => "cat" 
]; 

array_push($data, ['pussy' => 'wagon']); 

*在php 7及更高版本中,數組是使用[]創建的,而不是()

+0

兩個問題:'array_push'將其第二個+參數添加爲新值(而不是與array_merge一樣的鍵 - 值對),並且PHP 7愉快地接受'array()'數組語法(以及'''''句法) – 2017-08-15 16:15:09