php array_push() 带键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1355072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
array_push() with key value pair
提问by mistero
I have an existing array to which I want to add a value.
我有一个要添加值的现有数组。
I'm trying to achieve that using array_push()to no avail.
我正在尝试使用array_push()无济于事。
Below is my code:
下面是我的代码:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add catas a key to the $dataarray with wagonas value so as to access it as in the snippet below:
我想要实现的是将cat作为键添加到$data带有wagon作为值的数组中,以便像下面的代码片段一样访问它:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?
我怎样才能做到这一点?
回答by dusoft
So what about having:
那么拥有:
$data['cat']='wagon';
回答by Harijs Krūtainis
If you need to add multiple key=>value, then try this.
如果您需要添加多个 key=>value,请尝试此操作。
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
回答by rogeriopvl
$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.
这就是将键和值添加到数组所需的全部内容。
回答by Prince Patel
For Example:
例如:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
更改键值:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
输出:
数组( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
添加新的键值对:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )
输出:
数组 ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue)
回答by Deepak Vaishnav
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
您不需要使用 array_push() 函数,您可以使用新键直接将新值分配给数组,例如..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
回答by Mr-Faizan
Array['key'] = value;
数组['key'] = 值;
$data['cat'] = 'wagon';
This is what you need. No need to use array_push() function for this. Some time the problem is very simple and we think in complex way :) .
这就是你所需要的。无需为此使用 array_push() 函数。有时问题很简单,我们以复杂的方式思考:)。
回答by xayer
Just do that:
就这样做:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()
*在 php 7 及更高版本中,数组是使用 [] 创建的,而不是 ()

