2015-02-24 16 views
2

在我們的數據庫中,我們有一個表格是來自三個表格的每個排列結果。檢測多維數組中的新排列

我正在嘗試編寫一個PHP腳本,它將把所有這些表視爲數組,並檢測是否存在缺失的置換。

例如

$foo = array('one', 'two', NULL) 
$bar = array('three', 'four', NULL) 
$baz = array('five', 'six', NULL) 

$permutations = array(
    array('one', 'three', 'five'), 
    array('two', 'three', 'five'), 
    array(NULL, 'three', 'five'), 
    //etc 
) 

foreach $foo as $x 
    foreach $bar as $y 
    foreach $baz as $z 
     $combo = array($x, $y, $z) 
     if $combo is not in $permutations 
     //generate sql to update db 

我該如何做到這一點?

+3

如果你有X個表格,每個表格都有Y個元素(??),那麼如果這是一個「重複排列」,那麼你將有X^Y個排列。所以,一個快速的煙霧測試會確保'$ permutations'的長度與X^Y相同(或者任何集合的範圍*應該是)......你也可以做一些事情來確保$ permutations有在進行長度檢查之前,只有唯一的元素。這可能比檢查每一個可能的排列更有效。 – wilkesybear 2015-02-24 01:37:06

回答

0

我不知道究竟你試圖做什麼,但我建議:

$foo = array('one', 'two', NULL); 
$bar = array('three', 'four', NULL); 
$baz = array('five', 'six', NULL); 

$permutations = array(
    array('one', 'three', 'five'), 
    array('two', 'three', 'five'), 
    array(NULL, 'three', 'five'), 
    //etc 
); 

$foobarbaz = array_merge($foo, $bar, $baz); 
foreach($foobarbaz as $k){ 
    if(!in_array($k, $permutations) { 
    $sql_trigger_start(); 
    } 
} 

誰得到這個問題的一個例子。 http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/

+0

array_merge不起作用。反正也不是這樣。 $ permutations數組當前包含$ foo,$ bar和$ baz數組的所有可能組合。然而,有時$ foo,$ bar,$ baz數組會添加新項目,這意味着$ permutations數組不再包含每個組合。我需要一種方法來測試每個可能的組合對$ permutations數組,並檢測它不存在,以便我可以生成一個SQL語句。那有意義嗎? – pjmil 2015-02-24 02:51:04

+0

是的,謝謝你可以解決你的問題去這個鏈接http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/ – head 2015-02-24 08:58:28

2

你必須檢索與MySQL的每一個可能的排列,並使用LEFT 4日表連接和測試,如果沒有匹配

如果你有3個表T1,T2,T3包含一列「值」和表T4這是「置換」,其中包含三列T1,T2和T3,你可以得到不存在的「置換」與下面的查詢

SELECT t1.value v1, t2.value v2, t3.value v3 
FROM t1, t2, t3 
LEFT JOIN t4 ON t4.t1=v1 AND t4.t2=v2 AND t4.t3=v3 
WHERE t4.t1 IS NULL; 

您可以調整此查詢,以配合您的數據庫模式。

+0

你應該模擬一個完整的外部聯接來得到答案在一個查詢中。 – lnrdo 2015-02-24 09:47:35