PHP:合并两个数组,同时保持键,而不是重新索引? [英] PHP: merge two arrays while keeping keys instead of reindexing?
本文介绍了PHP:合并两个数组,同时保持键,而不是重新索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何合并两个数组(一个字符串=> value对,另一个带有int => value对),同时保持该字符串/ INT键?他们谁也不会重叠(因为一个只有字符串和其他的只有整数)。
下面是我目前的code(不工作,因为array_merge是重新索引整数键排列):
//获取所有的id瓦尔相结合,静态与动态
$ staticIdentifications =阵列(
用户::用户ID => 用户帐号,
用户名:: = GT; 用户名
);
//获取动态VAR,格式化:VARID => varName中
$ companyVarIdentifications = CompanyVars :: getIdentificationVarsFriendly($ _ SESSION ['companyID']);
//合并静态和动态VAR(***,但保留INT指数***)
$ idVars = array_merge($ staticIdentifications,$ companyVarIdentifications);
解决方案
您可以简单的'添加'数组:
>> $一个=阵列(1,2,3);
阵列(
0 => 1,
1 => 2,
2 => 3,
)
>> $ B =阵列(一=大于1,B=大于2,C=→3)
阵列(
'A'=> 1,
'B'=> 2,
'C'=> 3,
)
>> $ A + $ B
阵列(
0 => 1,
1 => 2,
2 => 3,
'A'=> 1,
'B'=> 2,
'C'=> 3,
)
How can I merge two arrays (one with string => value pairs and another with int => value pairs) while keeping the string/int keys? None of them will ever overlap (because one has only strings and the other has only integers).
Here is my current code (which doesn't work, because array_merge is re-indexing the array with integer keys):
// 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);
解决方案
You can simply 'add' the arrays:
>> $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,
)
这篇关于PHP:合并两个数组,同时保持键,而不是重新索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文