如何在键控数组中添加多个元素?
array_add($myArray, 'key', 'a');
array_add($myArray, 'key-2', 'b');
有更好的方法吗?
答案 0 :(得分:4)
不需要任何其他自定义函数,因为在PHP
中有一个内置函数,它是array_merge,您可以像这样使用它:
$myArray = array('one' => 'TheOne', 'two' => 'TheTwo');
$array = array_merge($myArray, array('three' => 'TheThree', 'four' => 'TheFour'));
print_r($array);
输出:
Array
(
[one] => TheOne
[two] => TheTwo
[three] => TheThree
[four] => TheFour
)
您也可以使用:
$myArray1 = array('one' => 'TheOne', 'two' => 'TheTwo');
$myArray2 = array('three' => 'TheThree', 'four' => 'TheFour');;
$array = $myArray1 + $myArray2;
print_r($array);
输出:
Array
(
[one] => TheOne
[two] => TheTwo
[three] => TheThree
[four] => TheFour
)
答案 1 :(得分:3)
我更喜欢:
$myArray['key'] = 'a';
$myArray['key-2'] = 'b';
但这并不是更好,因为你不会在一个命令中添加多个。
如果你真的需要添加多个,你总是可以创建一个帮手:
function array_add_multiple($array, $items)
{
foreach($items as $key => $value)
{
$array = array_add($items, $key, $value);
}
return $array;
}
并将其用作
$array = array_add_multiple($array, ['key' => 'a', 'key-2' => 'b']);
或者,如果您不使用PHP 5.4:
$array = array_add_multiple($array, array('key' => 'a', 'key-2' => 'b'));
答案 2 :(得分:0)
我的自定义“动态”方法:
function add_to_array($key_value)
{
$arr = [];
foreach ($key_value as $key => $value) {
$arr[] = [$key=>$value];
}
return $arr;
}
dd(add_to_array(["hello"=>"from this array","and"=>"one more time","what"=>"do you think?"]));