PHP : 다시 색인화하는 대신 키를 유지하면서 두 개의 배열을 병합 하시겠습니까? 가진 것)을 병합 할 수 있습니까?

string / 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);



답변

간단히 배열을 ‘추가’할 수 있습니다.

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


답변

당신이 가진 것을 고려

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

다음 $merge = $replacement + $replaced;을 출력합니다 :

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

합계의 첫 번째 배열에는 최종 출력에 값이 있습니다.

다음 $merge = $replaced + $replacement;을 출력합니다 :

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


답변

이 질문은 꽤 오래되었지만 키를 유지하면서 병합을 수행 할 수있는 또 다른 가능성을 추가하고 싶습니다.

+부호를 사용하여 기존 배열에 키 / 값을 추가하는 것 외에도 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도 하위 어레이에 대해이 작업을 수행한다.

3v4l.org의 라이브 예


답변

+ 연산자로 원래 색인을 생성하지 않고도 두 개의 배열을 쉽게 추가하거나 결합 할 수 있습니다 . 이것은 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',
 );


답변

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


답변