PHP:合并两个数组,同时保留键而不是重新索引?

标签 php arrays array-merge

如何在保留字符串/整数键的同时合并两个数组(一个带有字符串 => 值对,另一个带有 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);

最佳答案

您可以简单地“添加”数组:

>> $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:合并两个数组,同时保留键而不是重新索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3292044/

相关文章:

javascript - 显示和隐藏虚 url 中的内容

php - 与 nl2br 类似的函数,但使用 <w :br/> tags and removing any break lines

javascript - Ajax post 带有参数数组,然后在 PHP 中引用

c++ - 在 C++ 中使用合并函数算法时遇到问题

php - 如何使用 tcpdf 将条形码写入单元格

PHP文件上传(通过命令行上的Curl)

c - 搜索并打印输入文件中所有不重复的结构名称

c# - 如何在 C# 中对二维数组进行排序

javascript - 如何将数组展平或旋转为单个对象?

PHP - 多维数组合并为一个数组