这是我第一次在这里发帖,虽然我在这里阅读了很多很棒的技巧和技巧。
这是我的目标:
我有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
还应该注意的是,我并不关心Keys,只关注价值观。最终,这些值将被用于INSERT语句,但目前我只需要获得正确的结果。
无论如何,感谢任何和所有的帮助!
答案 0 :(得分:1)
这通常在SQL
中完成如果您希望整行在另一个表中至少有一个匹配的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交叉变体中,您需要单独构建数组,然后使用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>';