4

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

这是我的目标:

我有 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 语句中起作用,但目前我只需要得到正确的结果。

无论如何,感谢您的任何帮助!

4

1 回答 1

1

这通常在 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>';
于 2012-10-13T00:32:25.137 回答