array_push()与键值对
我有一个现有的数组,我想要添加一个值。array_push()与键值对
我试图实现,使用array_push()
无济于事。
下面是我的代码:
$data = array(
"dog" => "cat"
);
array_push($data['pussy'], 'wagon');
我想实现的是作为重点与货车添加猫到$data
数组值,以访问它,如下面的代码片段:
echo $data['pussy']; // the expected output is: wagon
我该如何做到这一点?
那么,关于有:
$data['pussy']='wagon';
$data['pussy'] = 'wagon';
这就是你需要添加键和值的数组。
如果您需要添加多个key =>值,请尝试此操作。
$data = array_merge($data, array("pussy"=>"wagon","foo"=>"baar"));
这不会在数组中添加任何值。 – 2015-11-22 06:19:47
它增加或改变现有的键。请RTFM。 – 2015-11-30 09:20:47
例如:
$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)以
只要做到这一点:
$data = [
"dog" => "cat"
];
array_push($data, ['pussy' => 'wagon']);
*在php 7及更高版本中,数组是使用[]创建的,而不是()
两个问题:'array_push'将其第二个+参数添加为新值(而不是与array_merge一样的键 - 值对),并且PHP 7愉快地接受'array()'数组语法(以及'''''句法) – 2017-08-15 16:15:09
如果猫是在一个变量? $ pussy ='pussy'; $ data [$ pussy] ='wagon'; 试试这个,它给了我一个错误 – Dynelight 2014-10-05 20:26:55
@Dynelight这不会给我一个错误;你得到的错误究竟是什么? – 2017-08-15 16:09:36
感谢您的回答和幽默。 ;-) – 2017-09-07 17:44:58