合并两个数字键关联数组并保留原始键

发布于 2024-11-18 04:00:11 字数 533 浏览 4 评论 0原文

我有两个这样的数组:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

我想组合这两个数组,使其不包含重复项并保留其原始键。例如输出应该是:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

我已经尝试过这个,但它正在改变它们的原始键:

$output = array_unique( array_merge( $array1 , $array2 ) );

有什么解决方案吗?

I have two arrays like this:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

I have tried this but it is changing their original keys:

$output = array_unique( array_merge( $array1 , $array2 ) );

Any solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

柳若烟 2024-11-25 04:00:11

只需使用:

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

这应该可以解决它。因为如果一个键出现多次(如示例中的 '44'),则您使用字符串键,一个键将覆盖前面的同名键。因为在您的情况下,它们都具有相同的值,无论如何这并不重要,而且它还会删除重复项。

更新:我刚刚意识到,PHP 将数字字符串键视为数字(整数),因此行为会像这样,这意味着它也会对键重新编号...

解决方法是重新创建键。

$output = array_combine($output, $output);

更新2:我总是忘记,还有一个运算符(粗体,因为这确实你正在寻找!:D)

$output = $array1 + $array2;

所有这些都可以看到在:
http://php.net/manual/en/function.array-merge。 php

Just use:

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

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in:
http://php.net/manual/en/function.array-merge.php

半步萧音过轻尘 2024-11-25 04:00:11

您应该考虑 $array1 + $array2 != $array2 + $array1

$array1 = array(
'11' => 'x1',
'22' => 'x1' 
);  

$array2 = array(
'22' => 'x2',
'33' => 'x2' 
);

$array1 + $array2

$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);

$array2 + $array1

$array2 + $array1 = array(  
'11' => 'x1',  
'22' => 'x2',  
'33' => 'x2'  
);

You should take to consideration that $array1 + $array2 != $array2 + $array1

$array1 = array(
'11' => 'x1',
'22' => 'x1' 
);  

$array2 = array(
'22' => 'x2',
'33' => 'x2' 
);

with $array1 + $array2

$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);

and with $array2 + $array1

$array2 + $array1 = array(  
'11' => 'x1',  
'22' => 'x2',  
'33' => 'x2'  
);
墨离汐 2024-11-25 04:00:11

这有效:

$output = $array1 + $array2;

This works:

$output = $array1 + $array2;
北斗星光 2024-11-25 04:00:11

使用 php7.4 执行此操作的新方法是 Spread 运算符 [...]

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);

Spread 运算符应该具有比 array_merge 更好的性能,

这是一个显着的优势Spread 运算符的一个特点是它支持任何可遍历的对象,而 array_merge 函数只支持数组。

The new way of doing it with php7.4 is Spread operator [...]

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);

Spread operator should have better performance than array_merge

A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.

初懵 2024-11-25 04:00:11

为此,您可以循环遍历一个并附加到另一个:

<?php

$test1 = array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

$test2 = array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);


function combineWithKeys($array1, $array2)
{
    foreach($array1 as $key=>$value) $array2[$key] = $value;
    asort($array2);
    return $array2;
} 

print_r(combineWithKeys($test1, $test2));

?>

更新:KingCrunch 提出了最佳解决方案print_r($array1+$array2);

To do this, you can loop through one and append to the other:

<?php

$test1 = array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

$test2 = array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);


function combineWithKeys($array1, $array2)
{
    foreach($array1 as $key=>$value) $array2[$key] = $value;
    asort($array2);
    return $array2;
} 

print_r(combineWithKeys($test1, $test2));

?>

UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);

温柔戏命师 2024-11-25 04:00:11

这有效:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

This works:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);
早茶月光 2024-11-25 04:00:11

警告! $array1 + $array2 覆盖键,所以我的解决方案(对于多维数组)是使用 array_unique()

array_unique(array_merge($a, $b), SORT_REGULAR);

注意:

5.2.10+sort_flags 的默认值更改回 SORT_STRING。

5.2.9默认为 SORT_REGULAR。

5.2.8-默认为 SORT_STRING

完美工作。希望它有同样的帮助。

Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()

array_unique(array_merge($a, $b), SORT_REGULAR);

Notice:

5.2.10+ Changed the default value of sort_flags back to SORT_STRING.

5.2.9 Default is SORT_REGULAR.

5.2.8- Default is SORT_STRING

It perfectly works. Hope it helps same.

瑕疵 2024-11-25 04:00:11

如果您使用的是 PHP 7.4 或更高版本,则可以使用展开运算符 ...,如 PHP 文档中的以下示例:

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

function getArr() {
  return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']

$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']

function arrGen() {
    for($i = 11; $i < 15; $i++) {
        yield $i;
    }
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]

它的工作方式类似于 JavaScript ES6。

有关更多信息,请参阅 https://wiki.php.net/rfc/spread_operator_for_array

If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

function getArr() {
  return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']

$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']

function arrGen() {
    for($i = 11; $i < 15; $i++) {
        yield $i;
    }
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]

It works like in JavaScript ES6.

See more on https://wiki.php.net/rfc/spread_operator_for_array.

苹果你个爱泡泡 2024-11-25 04:00:11

https://www.php.net/manual/en/function。数组合并.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

https://www.php.net/manual/en/function.array-merge.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
如果没有 2024-11-25 04:00:11

@jchook 在他的一条评论中稍微探讨了这一点,但值得强调的是 + 并不像人们预期的那样一致。当您处理相同的键时,结果与array_merge不同。

$a1 = array(
    'hello',
    'world',
);

$a2 = array(
    'foo',
    'baz',
);

// Will NOT work - only outputs $a1
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    'a' => 'hello',
    'b' => 'world',
);

$a2 = array(
    'c' => 'foo',
    'd' => 'baz',
);

// Will work (however were a and b c and d - would equally fail
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    1=> 'hello',
    2=> 'world',
);

$a2 = array(
    3=>'foo',
    4=>'baz',
);

// Will work
print'<pre>';print_r($a1 + $a2);print'</pre>';

This is slightly explored by @jchook in one of his comments, but it is worth highlighting that the + is not as consistant as one might expect. When you are dealing with keys which are the same, the results are not the same as array_merge.

$a1 = array(
    'hello',
    'world',
);

$a2 = array(
    'foo',
    'baz',
);

// Will NOT work - only outputs $a1
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    'a' => 'hello',
    'b' => 'world',
);

$a2 = array(
    'c' => 'foo',
    'd' => 'baz',
);

// Will work (however were a and b c and d - would equally fail
print'<pre>';print_r($a1 + $a2);print'</pre>';

$a1 = array(
    1=> 'hello',
    2=> 'world',
);

$a2 = array(
    3=>'foo',
    4=>'baz',
);

// Will work
print'<pre>';print_r($a1 + $a2);print'</pre>';
度的依靠╰つ 2024-11-25 04:00:11

我们可以使用扩展运算符 (...) 在 PHP 中组合两个数组。

在此示例中,$array1 包含值 1 到 10,$array2 包含值 11 到 20。
扩展运算符用于将两个数组连接(组合)为一个名为 $data 的数组。

// Define the first array
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Define the second array
$array2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

// Use the spread operator to concatenate the two arrays into a single array
$data = [...$array1, ...$array2];

// Print the contents of the combined array
print_r($data);

We can combine two arrays in PHP using the spread operator (...).

In this example, $array1 contains the values 1 through 10, and $array2 contains the values 11 through 20.
The spread operator is used to concatenate(combine) the two arrays into a single array called $data.

// Define the first array
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Define the second array
$array2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

// Use the spread operator to concatenate the two arrays into a single array
$data = [...$array1, ...$array2];

// Print the contents of the combined array
print_r($data);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文