gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:51:53 24 4
gpt4 key购买 nike

有更好的方法吗? 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);

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

或者有什么方法可以在 MySQL 中做到这一点吗?如果是这样:

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

我需要执行两个步骤(两个 SELECT)来获取我需要的所有 id,但有时两个数组可以包含相同的 id,所以我需要过滤它。我不太擅长创建一些更复杂的 SQL 请求。可以创建这样的东西吗?

最佳答案

您可以使用单个查询来获取 UNION 的不同值:

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

UNION 没有关键字 ALL 将仅返回不同的行,在您的情况下是不同的值。

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

UNION is used to combine the result from multiple SELECT statementsinto a single result set....

The default behavior for UNION is that duplicate rows are removed from the result.

关于PHP,合并两个数组,删除相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24598162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com