I'm having a hard time elimination the duplicates out of my php foreach. I cant get it to work for some reason.
What I'm trying to do is as following: People are able to recommend other people to follow a specific user. If two people has recommended the same person, there are two db entries with the username of that specific user.
I've got a page full of recommendations by the logged in user. I show the users via foreach. Since there are two db entries of that specific person, that user got shown twice. Thats the reason why I want to eliminate duplicates and show every user just once, no matter how many people recommended that person.
I've tried everything I could think of. Even array_unique wouldnt do the trick for me, but thats because I'm comparing an array against a variable. But I seriously have no clue how to do it otherwise..
Here's a part of my code
//Get info about users recommendations and put them into an array
$prepare_user_info = array();
$get_user_info = mysqli_query($mysqli,"SELECT * FROM recommend WHERE rec_by_id = '$user_id' ORDER BY timestamp DESC") OR die (mysqli_error($mysqli));
while($prepared_user = mysqli_fetch_array($get_user_info)){
$prepared_user = array(
"rec_id" => $prepared_user['rec_id']);
$prepare_user_info[] = $prepared_user;
}
//Foreach every recommendation by the logged in user
foreach ($prepare_user_info as $pu):
//Get the recommendations user_data_array
$stmt = $mysqli->prepare("SELECT user_lookup_array FROM recommend WHERE rec_id = ?") or die (mysqli_error($mysqli));
$stmt->bind_param('s', $pu['rec_id']);
$stmt->execute();
$stmt->bind_result($db_user_data_array);
$stmt->store_result();
$stmt->fetch();
$fetch_array = $stmt->num_rows;
$stmt->close();
//Decode the user_data_array
$user = json_decode($db_user_data_array);
//Echo the name of the user
echo $user->name;
endforeach;
Is there any way to eliminate the duplicates, so every user only get shown once, no matter how many times the logged in user recommended that person?
Thanks in advance!
EDIT
I've changed my first piece of code into (thank you @Mike Brant):
$prepare_user_info = array();
$get_user_info = mysqli_query($mysqli,"SELECT DISTINCT rec_id FROM recommend WHERE rec_by_id = '$user_id' ORDER BY timestamp DESC") OR die (mysqli_error($mysqli));
while($prepared_user = mysqli_fetch_array($get_user_info)){
$prepared_user = array(
"rec_id" => $prepared_user['rec_id']);
$prepare_user_info[] = $prepared_user;
}
The duplicates are gone and the people are shown only once. However, one question remains. Why should I not prepare inside the foreach? I need the user_lookup_array of every user. Therefor I placed it inside the foreach.
Thanks!