Array_intersect in foreach loop

This is my first post here, although I got a lot of great tips and techniques reading posts here.

Here is my goal:

I have 2 several similar tables for comparison. For each row of each table, I pull out the fields that I want to get into an array.

I basically want to drop the values ​​of any array from one table that has the corresponding values ​​in another array.

Here is my code, maybe it will be easier to understand.

$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>'; } } 

Here are the results that I get for each iteration of the code:

 Array ( ) 1 

It should also be noted that I am not interested in keys, just meanings. In the end, these values ​​will work in the INSERT statement, but for now I just need to get the correct results.

Anyway, thanks for any help!

+4
source share
1 answer

This is usually done in SQL.

if you want the whole row to have at least 1 corresponding SKU in another table:

 $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); 

If you want only 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); 

In the PHP crossing option, you need to collect the arrays separately and then use 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>'; 
+1
source

Source: https://habr.com/ru/post/1439502/


All Articles