<?php
// $pdo is already declared as a working database connection by this sandbox
$table1Ids = [5, 5, 1, 3, 3];
$table2Ids = [2, 3, 1, 1, 2]; // assumed to always have identical length as $table1Ids
$zipFlattened = [];
foreach ($table1Ids as $index => $zipFlattened[]) {
$zipFlattened[] = $table2Ids[$index];
}
// $zipFlattened = [5, 2, 5, 3, 1, 1, 3, 1, 3, 2]
$uniqueIds2 = array_unique($table2Ids);
$placeholders1 = implode(',', array_fill(0, count($table1Ids), '(?,?)'));
$placeholders2 = implode(',', array_fill(0, count($uniqueIds2), '?'));
$sql = <<<SQL
SELECT *
FROM pivot
WHERE (table_1_id, table_2_id) NOT IN ($placeholders1)
AND table_2_id IN ($placeholders2)
AND is_active = 1
SQL;
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($zipFlattened, $uniqueIds2));
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC), JSON_PRETTY_PRINT);