我有一个现有的数组,我想添加一个值.
我试图实现这一点array_push(),但无济于事.
以下是我的代码:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
Run Code Online (Sandbox Code Playgroud)
我想要实现的是将cat作为$data数组的键添加到wagon作为值,以便访问它,如下面的代码片段所示:
echo $data['cat']; // the expected output is: wagon
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
dus*_*oft 308
那么有什么:
$data['cat']='wagon';
Run Code Online (Sandbox Code Playgroud)
Har*_*nis 43
如果你需要添加多个key => value,那么试试这个.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
Run Code Online (Sandbox Code Playgroud)
您不需要使用 array_push() 函数,您可以使用新键直接将新值分配给数组,例如..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
Run Code Online (Sandbox Code Playgroud)
例如:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
Run Code Online (Sandbox Code Playgroud)
要更改键值:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
Run Code Online (Sandbox Code Playgroud)
输出:
数组([firstKey] => changedValue [secondKey] => secondValue)
用于添加新的键值对:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
Run Code Online (Sandbox Code Playgroud)
输出:
数组([firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue)
小智 5
数组['键'] = 值;
$data['cat'] = 'wagon';
Run Code Online (Sandbox Code Playgroud)
这就是你所需要的。无需为此使用 array_push() 函数。有时问题很简单,我们却以复杂的方式思考:)。