programing

두 어레이를 "+"(어레이 유니온 연산자)와 병합하는 방법

itsource 2023. 5. 7. 21:34
반응형

두 어레이를 "+"(어레이 유니온 연산자)와 병합하는 방법

다음을 사용하여 두 배열의 데이터를 병합하는 것으로 보이는 코드가 있습니다.+=하지만 요소에 모든 요소가 포함된 것은 아닙니다.어떻게 작동합니까?

예:

$test = array('hi');
$test += array('test', 'oh');
var_dump($test);

출력:

array(2) {
  [0]=>
  string(2) "hi"
  [1]=>
  string(2) "oh"
}

무엇인가.+PHP의 배열에서 사용될 때의 평균?

언어 연산자에 대한 PHP 설명서의 인용.

+ 연산자는 왼쪽 배열에 추가된 오른쪽 배열을 반환합니다. 두 배열 모두에 있는 키의 경우 왼쪽 배열의 요소가 사용되고 오른쪽 배열의 일치 요소는 무시됩니다.

그래서 만약 당신이

$array1 = ['one',   'two',          'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz']; 

print_r($array1 + $array2);

얻게 될 것입니다.

Array
(
    [0] => one   // preserved from $array1 (left-hand array)
    [1] => two   // preserved from $array1 (left-hand array)
    [foo] => bar // preserved from $array1 (left-hand array)
    [2] => five  // added from $array2 (right-hand array)
)

그래서 논리는+는 다음 스니펫에 해당합니다.

$union = $array1;

foreach ($array2 as $key => $value) {
    if (false === array_key_exists($key, $union)) {
        $union[$key] = $value;
    }
}

C-level 구현의 세부 사항에 관심이 있는 경우 다음으로 이동하십시오.


참고로, 그것은+어레이를 결합하는 방식과는 다릅니다.

print_r(array_merge($array1, $array2));

당신에게 줄 것입니다.

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => baz // overwritten from $array2
    [2] => three // appended from $array2
    [3] => four  // appended from $array2
    [4] => five  // appended from $array2
)

자세한 예는 연결된 페이지를 참조하십시오.

이것을 사용하기 위한 가장 좋은 예는 구성 배열입니다.

$user_vars = array("username"=>"John Doe");
$default_vars = array("username"=>"Unknown", "email"=>"no-reply@domain.com");

$config = $user_vars + $default_vars;

$default_vars는 기본값에 대한 배열입니다.$user_vars어레이가 에 정의된 값을 덮어씁니다.$default_vars결측값:$user_vars이제 기본 변수입니다.$default_vars.

이렇게 하면 됩니다.print_r다음과 같이:

Array(2){
    "username" => "John Doe",
    "email" => "no-reply@domain.com"
}

이것이 도움이 되길 바랍니다!

이 연산자는 두 어레이를 결합합니다(array_merge 중복 키를 덮어쓰는 경우를 제외하고는 array_merge와 동일합니다).

어레이 연산자에 대한 설명서는 여기에 있습니다.

숫자 키를 보존해야 하는지 또는 느슨하게 하고 싶은 것이 없는지 주의하십시오.

$a = array(2 => "a2", 4 => "a4", 5 => "a5");
$b = array(1 => "b1", 3 => "b3", 4 => "b4");

조합

print_r($a+$b);
Array
(
    [2] => a2
    [4] => a4
    [5] => a5
    [1] => b1
    [3] => b3
)

합병하다

print_r(array_merge($a, $b));
Array
(
    [0] => a2
    [1] => a4
    [2] => a5
    [3] => b1
    [4] => b3
    [5] => b4
)

+operator는 array_replace()와 동일한 결과를 생성합니다.그러나 연산자 인수가 반대이기 때문에 결과 배열의 순서도 다를 수 있습니다.

이 페이지에서 다른 예제로 확장:

$array1 = array('one', 'two', 'foo' => 'bar');
$array2 = array('three', 'four', 'five', 'foo' => 'baz'); 

print_r($array1 + $array2);
print_r(array_replace($array2, $array1)); //note reversed argument order

출력:

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => bar // preserved from $array1
    [2] => five  // added from $array2
)
Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [2] => five  // added from $array2
    [foo] => bar // preserved from $array1
)
  1. 배열 더하기 작업은 모든 배열을 연결 배열로 처리합니다.
  2. 더하기 도중 키가 충돌하면 왼쪽(이전) 값이 유지됩니다.

저는 상황을 분명히 하기 위해 아래 코드를 게시합니다.

$a + $b = array_plus($a, $b)

function array_plus($a, $b){
    $results = array();
    foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    return $results;
}

출처: https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/

그렇긴 하지만, 우리는 + 연산자가 array_replace 함수에서 동일한 것을 달성할 수 있기 때문에 일종의 중복이라고 생각할 수 있습니다.

그러나 $options 배열이 함수/메소드로 전달되고 있으며, 예비로 사용할 기본값도 있다고 가정하면 유용한 경우가 있습니다.

// we could do it like this
function foo(array $options)
{
   $defaults = ['foo' => 'bar'];
   
   $options = array_replace($defaults, $options);
 
   // ...
}
 
// but + here might be way better:
function foo(array $options)
{
   $options += ['foo' => 'bar'];
 
   // ...
}

새 배열이 이전 배열에 추가됩니다.

$var1 = "example";
$var2 = "test";
$output = array_merge((array)$var1,(array)$var2);
print_r($output);

배열 ( [0] => 예제 [1] => test )

언급URL : https://stackoverflow.com/questions/2140090/merging-two-arrays-with-the-array-union-operator-how-does-it-work

반응형