compare similarity between users PHP [closed]
-
22-12-2019 - |
Question
i'm making a site with a user system and want to match users by their profile which have like 20 fields
i want that users can get a match with an other user when they are above 50% which is 10 fields of the 20 the same
i already got this:
$query = "SELECT * FROM users WHERE username='test'";
$result = mysqli_query($db_conx, $query);
$array = mysqli_fetch_row($result);
$query2 = "SELECT * FROM users WHERE username='test2'";
$result2 = mysqli_query($db_conx, $query2);
$array2 = mysqli_fetch_row($result2);
$similar = array_intersect($array, $array2);
$p2_perc = count($similar) / count($array2);
echo round($p2_perc * 100) . "% equal";
i want that the users will automatically get that specific user displayed but i can fix that
anyone ?
thanks in advance appreciated very much!
the real question is like this
$query2 = "SELECT * FROM users LIMIT 1";
if ($query2 similarity > 50%)
echo "$user2";
Solution
You can combine this into one query like this:
SELECT
user1.username,
user2.username,
(
(user1.row1=user2.row1) +
(user1.row2=user2.row2) +
...
)/20 AS score
FROM
users AS user1,
users AS user2
WHERE
user1.username <> user2.username
HAVING
score > 0.5
This returns the two usernames and their score only it the score is greater than 0.5,
Explanation: The two columns get compared (each of the user1.rowX=user2.rowX
). If they're the same, it's 1
, else 0
. The sum of the 0's and 1's gets divided by the number of questions (20) and this is the score (it's a simple calculation of the average).
But this might get quite slow if you check a lot of users. If you want to display the matches only for a given user (e.g. who is logged in currently) use:
SELECT
user1.username,
user2.username,
(
(user1.row1=user2.row1) +
(user1.row2=user2.row2) +
...
)/20 AS score
FROM
users AS user1,
users AS user2
WHERE
user1.username <> user2.username AND
user1.username = 'CURRENTLY_LOGGED_IN_USER'
HAVING
score > 0.5