Alk
Alk

Reputation: 5557

PHP removing value within forEach loop from mysqli_fetch_array

I am running the following queries on my SQL databases. What I want to do next is to remove all the users from $result_users whose user_ID is also a receiverID in the $result_sender array. To do so I have created the following code, however I am not sure if my approach is correct. I have found online that what should be done is unset($array[$key]), however all the examples I found were normal arrays, and not obtained from SQL databases, hence I'm not sure how to proceed in this situation

 $retrieve_potential_matches_sender = mysqli_query($conn,"SELECT senderID, receiverID FROM match_instance WHERE senderID = '$sender'");
 $retrieve_all_users = mysqli_query($conn,"SELECT user_id, sex, latitude, longitude FROM users_with_fb");
 $result_sender = mysqli_fetch_array($retrieve_potential_matches_sender);
 $result_users = mysqli_fetch_array($retrieve_all_users);

 if count($result_sender) > 0 { 

 foreach ($result_sender as $sendingID) {

   foreach ($result_users as $userValue) { 

     if ($userValue["user_id"] == $sendingID["receiverID"] {

       unset($userValue);
    }
   }
 }

Upvotes: 0

Views: 102

Answers (2)

Reto
Reto

Reputation: 1343

You could do a sub query like this:

SELECT user_id, sex, latitude, longitude FROM users_with_fb WHERE user_id NOT IN (SELECT receiverID FROM match_instance);

Upvotes: 1

kunruh
kunruh

Reputation: 874

You are unsetting the variable used by the loop, not the value in the actual array. This should be what you are looking for:

foreach ($result_sender as $sendingID) {

  foreach ($result_users as $key => $userValue) { 

     if ($userValue["user_id"] == $sendingID["receiverID"] {

       unset($result_users[$key]);
     }
  }
}

Upvotes: 0

Related Questions