0
votes

i have a movie table and i want to compare the common movies of two users.

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

This will print

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

And for second user

$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);
This will print
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 ) )

When i compare these two arrays it gives me the first array.

$match= array_intersect($array1, $array2);
print_r($match);
The result will is
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 ) )

But the Common movies are: Snatch , The social network movie , once upon a time in the west

1
Why don't you do that in mysql?zerkms
Did you copy/paste this code directly from your source? Here you have $query3 pulling from the same user_id as $query2, so of course it would just print out everything in $array1tkm256
@zerkms: Because of poor DB designShakti Singh
@tkm256 sorry in query2 its user_id=2 not 1souce code
@Shakti Singh : How can i make strong db design in this scenario in which i want to compare the common movies of two users. what do you suggest....?souce code

1 Answers

1
votes

Try writing the following instead

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

That way the values in the arrays will be strings and can be compared easily. I don't know of the top of my head how array_intersect handles nested arrays but it works fine with strings.