我如何合并两个数组(一个与字符串=>值对和另一个与int =>值对),同时保持字符串/int键?它们都不会重叠(因为一个只有字符串,另一个只有整数)。
下面是我当前的代码(它不起作用,因为array_merge正在用整数键重新索引数组):
// get all id vars by combining the static and dynamic
$staticIdentifications = array(
Users::userID => "USERID",
Users::username => "USERNAME"
);
// get the dynamic vars, formatted: varID => varName
$companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']);
// merge the static and dynamic vars (*** BUT KEEP THE INT INDICES ***)
$idVars = array_merge($staticIdentifications, $companyVarIdentifications);
试试array_replace_recursive或array_replace函数
$a = array('userID' => 1, 'username'=> 2);
array (
userID => 1,
username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
'userID' => 1,
'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
userID => 1,
username => 2,
companyID => 3
)
http://php.net/manual/en/function.array-replace-recursive.php
可以很容易地添加或合并两个数组,而不需要通过+运算符更改它们的原始索引。这将非常有助于在laravel和codeigniter选择下拉菜单。
$empty_option = array(
''=>'Select Option'
);
$option_list = array(
1=>'Red',
2=>'White',
3=>'Green',
);
$arr_option = $empty_option + $option_list;
输出将是:
$arr_option = array(
''=>'Select Option'
1=>'Red',
2=>'White',
3=>'Green',
);
考虑到你已经
$replaced = array('1' => 'value1', '4' => 'value4');
$replacement = array('4' => 'value2', '6' => 'value3');
执行$merge = $replace + $replace;将输出:
Array('4' => 'value2', '6' => 'value3', '1' => 'value1');
sum中的第一个数组将在最终输出中有值。
执行$merge = $replace + $replace;将输出:
Array('1' => 'value1', '4' => 'value4', '6' => 'value3');
你可以简单地“添加”数组:
>> $a = array(1, 2, 3);
array (
0 => 1,
1 => 2,
2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
'a' => 1,
'b' => 2,
'c' => 3,
)
>> $a + $b
array (
0 => 1,
1 => 2,
2 => 3,
'a' => 1,
'b' => 2,
'c' => 3,
)
我只是想增加另一种可能性,在保留键的同时进行归并。
除了使用+号向现有数组添加键/值外,您还可以执行array_replace。
$a = array('foo' => 'bar', 'some' => 'string', 'me' => 'is original');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet', 'me' => 'is overridden');
$merged = array_replace($a, $b);
结果将是:
Array
(
[foo] => bar
[some] => string
[me] => is overridden
[42] => answer to the life and everything
[1337] => leet
)
相同的键将被后一个数组覆盖。
还有一个array_replace_recursive,它也为子数组做这个。
在3v4l.org上有一个活生生的例子
试试array_replace_recursive或array_replace函数
$a = array('userID' => 1, 'username'=> 2);
array (
userID => 1,
username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
'userID' => 1,
'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
userID => 1,
username => 2,
companyID => 3
)
http://php.net/manual/en/function.array-replace-recursive.php