Answers:
例如:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
更改键值:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
输出:
数组([firstKey] => changeValue [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)
您不需要使用array_push()函数,可以将带有新键的新值直接分配给数组。
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
$array['color3']='green'
。这正是@dusoft所做的。您的代码只是对该解决方案的混淆。
只需这样做:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*在php 7及更高版本中,数组是使用[]而不是()创建的
array_push
将其2nd +参数添加为新值(而不是键值配对array_merge
),PHP 7乐于接受array()
数组语法(以及速记[]
语法)
$a['123'] = 456;
-串“123”被转换为整数键123