2011-04-01 54 views
0

我有一個電影表,我想比較兩個用戶的普通電影。如何比較兩個mysql表php

 
$array1=array(); 
$array2=array(); 
$query2="select name from movie where user_id='2'"; 
$result2=mysql_query($query2) or die(mysql_error()); 
while($rss = mysql_fetch_assoc ($result2)) 
{ 
    $array1[]=$rss; 
} 
print_r($array1); 

這將打印

Array ([0] => Array ([name] => Snatch) [1] => Array ([name] => The Social Network Movie)
[2] => Array ([name] => Death Note) [3] => Array ([name] => Titanic)
[4] => Array ([name] => Once Upon a Time in the West))

而對於第二個用戶

$query3="select name from movie where user_id=1"; 
$result3= mysql_query($query3) or die(mysql_error()); 
while($rss1= mysql_fetch_assoc($result3)) 
{ 
    $array2[]=$rss1; 
} 
print_r($array2);
這將打印

Array ([0] => Array ([name] => The Lord of the Rings Trilogy) [1] => Array ([name] => Snatch) 
[2] => Array ([name] => The Social Network Movie) [3] => Array ([name] => Scarface)
[4] => Array ([name] => Once Upon a Time in the West) [5] => Array ([name] => Legend of the Guardians: The Owls of Ga'Hoole) [6] => Array ([name] => Once Upon a Time in America)
[7] => Array ([name] => Butch Cassidy and the Sundance Kid) [8] => Array ([name] => Fracture)
[9] => Array ([name] => Invictus) [10] => Array ([name] => Pride and Glory) [11] => Array ([name] => Casablanca))

當我比較這兩個數組,它給我的第一陣列。

$match= array_intersect($array1, $array2); 
print_r($match);
結果將是
Array ([0] => Array ([name] => Snatch) [1] => Array ([name] => The Social Network Movie)
[2] => Array ([name] => Death Note) [3] => Array ([name] => Titanic)
[4] => Array ([name] => Once Upon a Time in the West))

但共同的電影有:Snatch , The social network movie , once upon a time in the west

+0

你爲什麼不在mysql中這樣做? – zerkms 2011-04-01 06:04:58

+0

您是直接從源代碼複製/粘貼這段代碼嗎?在這裏,你有$ query3從相同的user_id拉到$ query2,所以當然它只會打印出$ array1中的所有內容。 – tkm256 2011-04-01 06:07:29

+0

@zerkms:由於數據庫設計差 – 2011-04-01 06:10:53

回答

1

試着寫下面的,而不是

while($rss = mysql_fetch_assoc ($result2)) { $array1[]=$rss['name']; }

這樣陣列中的值將是字符串,而比較容易。我不知道array_intersect是如何處理嵌套數組的,但它對字符串很好用。