Program Club

PHP에서 2 개의 배열을 연결할 수 없습니다.

proclub 2021. 1. 10. 17:44
반응형

PHP에서 2 개의 배열을 연결할 수 없습니다.


최근에 PHP에서 + 연산자를 사용하여 2 개의 배열을 결합하는 방법을 배웠습니다.

그러나이 코드를 고려하십시오.

$array = array('Item 1');

$array += array('Item 2');

var_dump($array);

출력은

array (1) {[0] => string (6) "항목 1"}

이것이 작동하지 않는 이유는 무엇입니까? 속기를 건너 뛰고 사용하는 $array = $array + array('Item 2')것도 작동하지 않습니다. 열쇠와 관련이 있습니까?


둘 다 키가 0되며 배열을 결합하는 방법은 중복 항목을 축소합니다. array_merge()대신 사용해보십시오 .

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

배열의 요소가 다른 키를 사용 +했다면 연산자가 더 적절할 것입니다.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

편집 : 명확히하기 위해 코드 스 니펫 추가


다음 array_merge()
문서를 참조하십시오 :
http://php.net/manual/en/function.array-merge.php

하나 이상의 배열의 요소를 병합하여 하나의 값이 이전 배열의 끝에 추가되도록합니다. 결과 배열을 반환합니다.


+결합 연산자 (PHP에는 배열 용 연산자가 없음)와 다른 Union 연산자라고합니다. 설명을 명확하게 말합니다 :

+ 연산자는 오른 손잡이 배열의 나머지 키 요소를 왼손잡이에 추가하는 반면 중복 된 키는 덮어 쓰지 않습니다.

예를 들어 :

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

두 배열 모두 키가있는 항목이 하나 0있으므로 결과가 예상됩니다.

연결하려면 array_merge.


모든 이전 답변이 잘못되었습니다! merge는 실제로 배열을 병합합니다. 즉, 배열에 공통 항목이있는 경우 복사본 중 하나가 생략됩니다. 노조도 마찬가지입니다 .

I didn't find a "work-around" for this issue, but to actually do it manually...

here it goes:

<?php
$part1 = array(1,2,3);
echo "array 1 = \n";
print_r($part1);
$part2 = array(4,5,6);
echo "array 2 = \n";
print_r($part2);
$ans = NULL;
for ($i = 0; $i < count($part1); $i++) {
    $ans[] = $part1[$i];
}
for ($i = 0; $i < count($part2); $i++) {
    $ans[] = $part2[$i];
}
echo "after arrays concatenation:\n";
print_r($ans);
?>

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

$array3 = array_merge($array1, $array2);

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.


$array = array('Item 1');

array_push($array,'Item 2');

or

$array[] = 'Item 2';

It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.

Instead you must use array_merge()

$array = array_merge(array('Item 1'), array('Item 2'));

This works for non-associative arrays:

while(($item = array_shift($array2)) !== null && array_push($array1, $item));


Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.


you may use operator . $array3 = $array1.$array2;

ReferenceURL : https://stackoverflow.com/questions/2650177/cant-concatenate-2-arrays-in-php

반응형