Home > OS >  PHP, Compare 2 while loops
PHP, Compare 2 while loops

Time:02-24

I have these 2 while loops.

  1. Loop. Left side screen. Shows users attached to a task.
$getcurrentusers = $conn->prepare("SELECT u.userid, u.username, u.Fname, u.inactive, r.userid, r.job_id FROM users AS u INNER JOIN job_responsible AS r ON u.userid = r.userid WHERE u.inactive = 0 AND r.job_id = $getPostID ORDER BY u.Fname");
$getcurrentusers->execute();
$resultgetcurrentusers = $getcurrentusers->get_result();
$getcurrentusers->close();
  if ($resultgetcurrentusers->num_rows > 0) {
    while($row = $resultgetcurrentusers->fetch_assoc()) {
      echo $row["username"]." (".$row["Fname"].")<br />";
    }
  } else {
    echo "Der er ikke valgt nogle ansvarlige til denne opgave.";
  }?>
  1. Loop. Right side screen. List all possible users that can be added to the task
$getdepartmentview = $SetDepartmentView;
$explodegetdepartmentview = explode(",",$getdepartmentview);
$implodegetdepartmentview = "'".implode("','",$explodegetdepartmentview)."'";
$getusers = $conn->prepare("SELECT userid, username, Fname, inactive FROM users WHERE departmentid IN ($implodegetdepartmentview) AND inactive = 0 ORDER BY Fname");
$getusers->execute();
$resultgetusers = $getusers->get_result();
$getusers->close();
  if ($resultgetusers->num_rows > 0) {
    while($row = $resultgetusers->fetch_assoc()) { 
      echo "<input type=\"checkbox\" name=\"choose_responsible[]\" value=\"".$row["userid"].",\" />".$row["Fname"]."<br />";
    } 
  }

The problem is, I would really like, that the input checkbox is 'checked' on the right side when there is a match from the left side 1. loop.

So..

Loop 1 | Loop 2
name3  | name1
name5  | name2
name7  | name3 - Inputbox checked
name8  | name4
       | name5 - Inputbox checked
       | name6
       | name7 - Inputbox checked
       | name8 - Inputbox checked
       | name9
       | name10

Someone who can help me with that?

CodePudding user response:

In the first loop you can store user_id in an array

$user_ids[] = $row["userid"]

In the second loop you check the current user id if it exists in the previous saved $user_ids array

$checked = false;
if (in_array($row["userid"], $user_ids)) {
    $checked = true;
} 
  • Related