合并两个数组并删除php中的重复条目
Posted
技术标签:
【中文标题】合并两个数组并删除php中的重复条目【英文标题】:issue in merge two array and remove duplicate entry in php 【发布时间】:2021-10-20 05:08:36 【问题描述】:我已经合并了两个数组。重复条目被删除。 以我为例来解释一下
$array1 = array("2", "3");
$array2 = array("3", "5", "4", "7", "8", "2", "10");
我已合并 array1 和 array2 $oneMeargeArr = array_merge($array1, $array2);
数组合并输出
$oneMeargeArr = Array ( [0] => 2 [1] => 3 [2] => 3 [3] => 5 [4] => 4 [5] => 7 [6] => 8 [7] => 2 [8] => 10)
之后删除重复条目
$oneMeargeArr = Array ( [0] => 3 [1] => 5 [2] => 4 [3] => 7 [4] => 8 [5] => 2 [6] => 10)
我得到这样的输出
$test_array = Array ( [0] => 3 [1] => 5 [2] => 4 [3] => 7 [4] => 8 [5] => 2 [6] => 10)
我想要这样的输出
$test_array = Array ( [0] => 5 [1] => 4 [2] => 7 [3] => 8 [4] => 10)
【问题讨论】:
合并数组的代码在哪里? 你可能需要这个***.com/questions/13469803/… @RobbertvandenBogerd $array1 = array("2", "3"); $array2 = 数组(“3”、“5”、“4”、“7”、“8”、“2”、“10”);我已经合并了 array1 和 array2 $oneMeargeArr = array_merge( $array1, $array2);数组合并输出 $oneMeargeArr = Array ( [0] => 2 [1] => 3 [2] => 3 [3] => 5 [4] => 4 [5] => 7 [6] => 8 [7] => 2 [8] => 10) 之后删除重复条目 $oneMeargeArr = Array ( [0] => 3 [1] => 5 [2] => 4 [3] => 7 [4] => 8 [5] => 2 [6] => 10) 【参考方案1】:使用下面的代码:
$array1 = array("2", "3");
$array2 = array("3", "5", "4", "7", "8", "2", "10");
$test_array = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
var_dump($test_array);
上面的代码会输出:
array(5)
[3]=>
string(1) "5"
[4]=>
string(1) "4"
[5]=>
string(1) "7"
[6]=>
string(1) "8"
[8]=>
string(2) "10"
要重新设置从0
开始的数组索引,请再次执行以下操作:
array_values($test_array);
【讨论】:
此解决方案有效,但我的数组是 Array $array1 = ( [0] => Array([id] => 44 [user_id] => 2 [name] => jina_testl [profilePhoto] = >)) ) $array2 = Array([0] => Array( [id] => 2 [user_id] => 3 [name] => demo_test1 [profilePhoto] => ) [1] => Array([id] => 45 [user_id] => 2 [name] => jina_testl [profilePhoto] =>)) 您对这个数组的解决方案不起作用。我已经与 user_id 进行比较以上是关于合并两个数组并删除php中的重复条目的主要内容,如果未能解决你的问题,请参考以下文章