在 PHP 中向关联数组添加值

php
2022-08-30 11:39:08

我想将一个元素追加到关联数组的末尾。

例如,我的数组是

$test=Array ([chemical] => asdasd [chemical_hazards] => ggggg ) 

我的结果应该是

$test=Array ([chemical] => asdasd [chemical_hazards] => ggggg [solution] => good) 

你能告诉我如何实现这一点吗?


答案 1

只需像使用非关联数组一样添加它:

$test = array('chemical' => 'asdasd', 'chemical_hazards' => 'ggggg'); //init
$test['solution'] = 'good';

答案 2

您可以使用PHP的array_merge函数来执行此操作。

$test = array('chemical' => 'asdasd', 'chemical_hazards' => 'ggggg'); 
$test2 = array('solution' => 'good');
$result = array_merge($test, $test2);
var_dump($result);

推荐