简体   繁体   English

PHP,合并两个数组,删除相同的值

[英]PHP, merge two arrays, remove the same values

Is there a better way how to do it? 有没有更好的方法呢? Some one function in PHP? PHP中的某个功能?

  $a = array(1, 2, 3, 4, 5, 6);
  $b = array(1, 2, 8, 9, 10, 3, 20);

  $c = array_merge($a, $b);
  $c = array_unique($c);

Result: 1, 2, 3, 4, 5, 6, 8, 9, 10, 20 结果:1、2、3、4、5、6、8、9、10、20

Or is there some way how to do it in MySQL? 还是有某种方法可以在MySQL中做到这一点? In case that: 在以下情况下:

$a = getMySQLArray("SELECT id FROM table1 WHERE ...")
$b = getMySQLArray("SELECT id FROM table2 WHERE ...")

I need to do two steps(two SELECT) to get all ids which I need but sometimes both array can contain the same id so I need to filter it. 我需要执行两个步骤(两个SELECT)来获取所需的所有ID,但有时两个数组都可以包含相同的ID,因此我需要对其进行过滤。 I'm not so expert with SQL to create some more complex SQL request. 我不太擅长使用SQL创建一些更复杂的SQL请求。 It is possible to create something like this? 可以创建这样的东西吗?

You can use a single query to get those distinct values with UNION : 您可以使用单个查询通过UNION获取那些不同的值:

SELECT 
    id 
FROM table1 WHERE ...
UNION
SELECT 
    id 
FROM table2 WHERE ...

UNION without the keyword ALL will only return distinct rows, in your case distinct values. 没有关键字ALL UNION将仅返回不同的行,在这种情况下,将返回不同的值。

SELECT ...
UNION [ALL | DISTINCT] SELECT ...
[UNION [ALL | DISTINCT] SELECT ...]

UNION is used to combine the result from multiple SELECT statements into a single result set. UNION用于将来自多个SELECT语句的结果合并为一个结果集。 ... ...

The default behavior for UNION is that duplicate rows are removed from the result. UNION的默认行为是从结果中删除重复的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM