duanlie2709 2010-08-17 22:17
浏览 29
已采纳

从2个数组中获取唯一值

I have 2 arrays that I'm trying to get the unique values only from them. So I'm not just trying to remove duplicates, I'm actually trying to remove both duplicates.

So if I'm getting the 2 arrays like this:

$array1 = array();
$array2 = array();

foreach($values1 as $value1){ //output: $array1 = 10, 15, 20, 25;
    $array1[] = $value1;
}   

foreach($values2 as $value2){ //output: $array2 = 10, 15, 100, 150;
    $array2[] = $value2;
}

The final output I'm looking for is

$output = 20, 25, 100, 150;

Any neat way to getting this done?

  • 写回答

7条回答 默认 最新

  • dopmgo4707 2010-08-17 22:25
    关注

    The other answers are on the right track, but array_diff only works in one direction -- ie. it returns the values that exist in the first array given that aren't in any others.

    What you want to do is get the difference in both directions and then merge the differences together:

    $array1 = array(10, 15, 20, 25);
    $array2 = array(10, 15, 100, 150);
    $output = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
    // $output will be (20, 25, 100, 150);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效