簡體   English   中英

帶有鍵值對的array_push()

[英]array_push() with key value pair

我有一個想要添加值的現有數組。

我正在嘗試使用array_push()來實現這一點,但無濟於事。

下面是我的代碼:

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

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

我想要實現的是將cat作為鍵添加到$data數組中,並以wagon作為值,以便像下面的代碼片段一樣訪問它:

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

我怎樣才能做到這一點?

那么擁有:

$data['cat']='wagon';

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

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';

這就是將鍵和值添加到數組所需的全部內容。

您不需要使用 array_push() 函數,您可以使用新鍵直接將新值分配給數組,例如..

$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);


Output:

   Array(
     [color1] => red
     [color2] => blue
     [color3] => green
   )

例如:

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

數組['key'] = 值;

$data['cat'] = 'wagon';

這就是你所需要的。 無需為此使用 array_push() 函數。 有時問題很簡單,我們以復雜的方式思考:)。

<?php
$data = ['name' => 'Bilal', 'education' => 'CS']; 
$data['business'] = 'IT';  //append new value with key in array
print_r($data);
?>

結果

Array
(
    [name] => Bilal
    [education] => CS
    [business] => IT
)

就這樣做:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM