gpt4 book ai didi

php - foreach 循环中的 array_intersect

转载 作者:可可西里 更新时间:2023-10-31 23:42:19 24 4
gpt4 key购买 nike

这是我第一次在这里发帖,虽然我在阅读这里的帖子时得到了很多很棒的提示和技巧。

这是我的目标:

我有 2 个比较相似的表格。对于每个表的每一行,我将我想要的字段拉到一个数组中。

我基本上想从一个表中回显任何数组的值,该表在另一个数组中具有匹配值。

这是我的代码,也许会更容易理解。

$sql = "SELECT * FROM $i_comp ORDER BY `manufacturer`";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);

$sql = "SELECT `sku_one`,`sku_two`,`qty`,`manufacturer`";
$sql .= "FROM $i_gas ORDER BY `manufacturer`";
$statement = $objDb->query($sql);
$d_skus = $statement->fetchAll(PDO::FETCH_ASSOC);

foreach ( $c_skus as $c_sku ) {
// i want to see if any values of this array exist in the array created hy
// the foreach loop below (yes, repeat for each row)
$c = array($c_sku['sku'],$c_sku['sku_one'],$c_sku['sku_two'],$c_sku['sku_three']);
foreach ( $d_skus as $d_sku ) {
$d = array($d_sku['sku_one'],$d_sku['sku_two']);
$intersect = array_intersect($c, $d);
echo '<pre>', print_r($intersect), '</pre>';
}
}

以下是我收到的每次代码迭代的结果:

Array
(
)
1

还应注意,我不关心键,只关心值。最终,这些值将用于 INSERT 语句,但目前我只需要获得正确的结果。

无论如何,感谢您提供的所有帮助!

最佳答案

这通常在 SQL 中完成

如果您想要在另一个表中至少有 1 个匹配 SKU 的整行:

$sql = "
SELECT c.* FROM $i_comp AS c
JOIN $i_gas AS d
ON d.sku_one in (c.sku, c.sku_one, c.sku_two, c.sku_three)
OR d.sku_two in (c.sku, c.sku_one, c.sku_two, c.sku_three)
ORDER BY c.`manufacturer`";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
// all rows that have at least 1 matching sku on another table
print_r($c_skus);

如果您只想要 SKU

$sql = "
SELECT d.sku_one FROM $i_comp AS c
JOIN $i_gas AS d
ON d.sku_one in (c.sku, c.sku_one, c.sku_two, c.sku_three)
UNION
SELECT d.sku_two FROM $i_comp AS c
JOIN $i_gas AS d
OR d.sku_two in (c.sku, c.sku_one, c.sku_two, c.sku_three)
";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
// all skus that have at least 1 matching sku on another table
print_r($c_skus);

在 PHP intersect 变体中,您需要单独构建数组,然后使用 array_intersect

$c = array();
foreach ( $c_skus as $c_sku ) {
$c[] = $c_sku['sku'];
$c[] = $c_sku['sku_one'];
$c[] = $c_sku['sku_two'];
$c[] = $c_sku['sku_three'];
}
$d = array();
foreach ( $d_skus as $d_sku ) {
$d[] = $d_sku['sku_one'];
$d[] = $d_sku['sku_two'];
}

$intersect = array_intersect($c, $d);
echo '<pre>', print_r($intersect), '</pre>';

关于php - foreach 循环中的 array_intersect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868593/

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