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

问题描述 投票:239回答:5

如何合并两个数组(一个带有字符串=>值对,另一个带有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);
php arrays array-merge
5个回答
526
投票

您可以简单地'添加'数组:

>> $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,
)

57
投票

考虑到您有

$replaced = array('1' => 'value1', '4' => 'value4');
$replacement = array('4' => 'value2', '6' => 'value3');

正在执行$merge = $replacement + $replaced;将输出:

Array('4' => 'value2', '6' => 'value3', '1' => 'value1');

sum中的第一个数组将在最终输出中具有值。

正在执行$merge = $replaced + $replacement;将输出:

Array('1' => 'value1', '4' => 'value4', '6' => 'value3');

17
投票

虽然这个问题很老,我只想增加在保留键的同时进行合并的另一种可能性。

除了使用+符号向现有数组添加键/值之外,您还可以执行array_replace

$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');

$merged = array_replace($a, $b);

结果将是:

Array
(
  [foo] => bar
  [some] => string
  [42] => answer to the life and everything
  [1337] => leet
)

相同的键将被后面的数组覆盖。还有一个array_replace_recursive,它也对子数组执行此操作。

Live example on 3v4l.org


3
投票

两个数组可以很容易地添加或合并,而无需通过+运算符更改其原始索引。这对于laravel和codeigniter select下拉列表将非常有帮助。

 $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',
 );

1
投票

尝试使用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

© www.soinside.com 2019 - 2024. All rights reserved.