Gar*_*ett 241 php arrays array-merge
如何在保留字符串/ int键的同时合并两个数组(一个使用string => value对,另一个使用int => value对)?它们都不会重叠(因为一个只有字符串而另一个只有整数).
这是我当前的代码(不起作用,因为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);
Run Code Online (Sandbox Code Playgroud)
Sir*_*ius 533
你可以简单地'添加'数组:
>> $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,
)
Run Code Online (Sandbox Code Playgroud)
CRK*_*CRK 57
考虑到你有
$replaced = array('1' => 'value1', '4' => 'value4');
$replacement = array('4' => 'value2', '6' => 'value3');
Run Code Online (Sandbox Code Playgroud)
做$merge = $replacement + $replaced;会输出:
Array('4' => 'value2', '6' => 'value3', '1' => 'value1');
Run Code Online (Sandbox Code Playgroud)
sum中的第一个数组将在最终输出中包含值.
做$merge = $replaced + $replacement;会输出:
Array('1' => 'value1', '4' => 'value4', '6' => 'value3');
Run Code Online (Sandbox Code Playgroud)
dan*_*opz 18
虽然这个问题已经很老了,但我只是希望在保留密钥的同时增加另一种合并的可能性.
除了使用+符号向现有阵列添加键/值之外,您还可以执行此操作array_replace.
$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');
$merged = array_replace($a, $b);
Run Code Online (Sandbox Code Playgroud)
后一个数组将覆盖相同的密钥.
还有一个array_replace_recursive,也用于子阵列.