Programing

PHP는 하나의 배열을 다른 배열에 추가합니다 (array_push 또는 + 아님)

lottogame 2020. 4. 9. 07:58
반응형

PHP는 하나의 배열을 다른 배열에 추가합니다 (array_push 또는 + 아님)


키를 비교하지 않고 한 배열을 다른 배열에 추가하는 방법은 무엇입니까?

$a = array( 'a', 'b' );
$b = array( 'c', 'd' );

말은해야한다 : Array( [0]=>a [1]=>b [2]=>c [3]=>d )내가 좋아하는 뭔가를 사용하는 경우 []또는 array_push, 그 결과 중 하나가 발생합니다 :

Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) )
//or
Array( [0]=>c [1]=>d )

이것은 무언가를해야하지만보다 우아한 방식으로해야합니다.

foreach ( $b AS $var )
    $a[] = $var;

array_merge 우아한 방법입니다 :

$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b); 
// $merge is now equals to array('a','b','c','d');

같은 일을 :

$merge = $a + $b;
// $merge now equals array('a','b')

+연산자가 실제로 병합하지 않기 때문에 작동하지 않습니다. 그들이 경우 $a와 동일한 키를 가지고 $b, 그것은 아무것도하지 않습니다.


PHP 5.6+에서이를 수행하는 또 다른 방법은 ...토큰 을 사용하는 것입니다

$a = array('a', 'b');
$b = array('c', 'd');

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

이것은 또한 Traversable

$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

경고 하지만 :

  • 7.3 이전의 PHP 버전에서는 $b배열이 비어 있거나 빈 배열 일 경우 치명적 오류가 발생합니다.
  • PHP 7.3에서는 $b통과 할 수 없는 경우 경고가 발생합니다

왜 사용하지

$appended = array_merge($a,$b); 

올바른 내장 방법을 사용하고 싶지 않습니까?


<?php
// Example 1 [Merging associative arrays. When two or more arrays have same key
// then the last array key value overrides the others one]

$array1 = array("a" => "JAVA", "b" => "ASP");
$array2 = array("c" => "C", "b" => "PHP");
echo " <br> Example 1 Output: <br>";
print_r(array_merge($array1,$array2));

// Example 2 [When you want to merge arrays having integer keys and
//want to reset integer keys to start from 0 then use array_merge() function]

$array3 =array(5 => "CSS",6 => "CSS3");
$array4 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 2 Output: <br>";
print_r(array_merge($array3,$array4));

// Example 3 [When you want to merge arrays having integer keys and
// want to retain integer keys as it is then use PLUS (+) operator to merge arrays]

$array5 =array(5 => "CSS",6 => "CSS3");
$array6 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 3 Output: <br>";
print_r($array5+$array6);

// Example 4 [When single array pass to array_merge having integer keys
// then the array return by array_merge have integer keys starting from 0]

$array7 =array(3 => "CSS",4 => "CSS3");
echo " <br> Example 4 Output: <br>";
print_r(array_merge($array7));
?>

산출:

Example 1 Output:
Array
(
[a] => JAVA
[b] => PHP
[c] => C
)

Example 2 Output:
Array
(
[0] => CSS
[1] => CSS3
[2] => JAVASCRIPT
[3] => HTML
)

Example 3 Output:
Array
(
[5] => CSS
[6] => CSS3
[8] => JAVASCRIPT
[9] => HTML
)

Example 4 Output:
Array
(
[0] => CSS
[1] => CSS3
)

참조 소스 코드


꽤 오래된 게시물이지만 한 배열을 다른 배열에 추가하는 방법을 추가하고 싶습니다.

만약

  • 하나 또는 두 배열 모두에 연관 키가 있습니다
  • 두 배열의 키는 중요하지 않습니다

다음과 같은 배열 함수를 사용할 수 있습니다.

array_merge(array_values($array), array_values($appendArray));

array_merge는 숫자 키를 병합하지 않으므로 $ appendArray의 모든 값을 추가합니다. foreach-loop 대신 native php 함수를 사용하는 동안 많은 요소를 가진 배열에서 더 빠릅니다.


큰 배열의 경우 메모리 복사를 피하기 위해 array_merge없이 연결하는 것이 좋습니다.

$array1 = array_fill(0,50000,'aa');
$array2 = array_fill(0,100,'bb');

// Test 1 (array_merge)
$start = microtime(true);
$r1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);

// Test2 (avoid copy)
$start = microtime(true);
foreach ($array2 as $v) {
    $array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);


// Test 1: 0.004963
// Test 2: 0.000038

bstoney와 Snark의 대답에서 나는 다양한 방법에 대해 몇 가지 테스트를 수행했습니다.

$array1 = array_fill(0,50000,'aa');
$array2 = array_fill(0,50000,'bb');

// Test 1 (array_merge)
$start = microtime(true);
$array1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);

// Test2 (foreach)
$start = microtime(true);
foreach ($array2 as $v) {
    $array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);

// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$start = microtime(true);
array_push($array1, ...$array2);
echo sprintf("Test 3: %.06f\n", microtime(true) - $start);

어느 생산 :

Test 1: 0.008392 
Test 2: 0.004626 
Test 3: 0.003574

필자는 PHP 7부터 foreach 루프가 작동 하는 방식으로 인해 방법 3이 훨씬 더 나은 대안이라고 생각합니다 . 이는 반복되는 배열의 사본을 만드는 것입니다.

방법 3이 질문에서 'not array_push'의 기준에 대한 대답은 아니지만, 한 줄이며 모든면에서 가장 높은 성능이지만 질문은 ... 구문이 옵션이라고 생각했습니다.


PHP7 이전에는 다음을 사용할 수 있습니다.

array_splice($a, count($a), 0, $b);

array_splice()배열 (첫 번째 인수)을 참조하여 작동하고 두 번째 인수에서 시작한 값 목록과 세 번째 인수 수 대신 배열 (4 번째 인수) 값을 넣습니다. 두 번째 인수를 소스 배열의 끝으로 설정하고 세 번째 인수를 0으로 설정하면 첫 번째 인수에 네 번째 인수 값을 추가합니다


빈 배열을 기존의 새 값과 병합하려는 경우. 먼저 초기화해야합니다.

$products = array();
//just example
for($brand_id=1;$brand_id<=3;$brand_id++){
  array_merge($products,getByBrand($brand_id));
}
// it will create empty array
print_r($a);

//check if array of products is empty
for($brand_id=1;$brand_id<=3;$brand_id++){
  if(empty($products)){
    $products = getByBrand($brand_id);
  }else{
    array_merge($products,getByBrand($brand_id));
  }
}
// it will create array of products

도움을 바랍니다.


foreach 루프는 array_merge보다 빠르므로 기존 배열에 값을 추가하기 때문에 다른 배열의 끝에 배열을 추가하려면 대신 루프를 선택하십시오.

// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
    $chars[] = array_fill(0, 10, 'a');
}

// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    $new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec

// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    foreach ($splitArray as $value) {
        $new[] = $value;
    }
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster

이것은 어떤가요:

$appended = $a + $b;

참고 URL : https://stackoverflow.com/questions/4268871/php-append-one-array-to-another-not-array-push-or

반응형