PHP:合并两个数组同时保留键而不是重新索引? [英] PHP: merge two arrays while keeping keys instead of reindexing?
本文介绍了PHP:合并两个数组同时保留键而不是重新索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在保留 string/int 键的同时合并两个数组(一个带有 string => 值对,另一个带有 int => 值对)?它们都不会重叠(因为一个只有字符串,另一个只有整数).
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).
这是我当前的代码(它不起作用,因为 array_merge 正在使用整数键重新索引数组):
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屋!
查看全文