I am trying to create a Nested Checkbox List in PHP. For this I have written Below Code with Multiple Nested foreach loop inside while
<?php
$sql_concern="SELECT * FROM sister_concern where Base_user='$User_id' And Status='Active'";
$result_concern = mysqli_query($link,$sql_concern);
if(mysqli_num_rows($result_concern) > 0){
echo '<ul>';
while($row = mysqli_fetch_array($result_concern)){
$sisid=$row['Id'];
$name=$row['Name'];
$namearray[]=$name;
foreach($namearray as $data){
echo '<li style="list-style-type:none;"><input type="checkbox" name="sister_concern" id="chkMainConcern'.$sisid.'" value="'.$sisid.'" > '.$name.' </li>';
//fetch module Name for each concern
$sql_module="SELECT * FROM Module where Status='Active'";
$result_module = mysqli_query($link,$sql_module);
//this one coming duplicate
echo '<ul style="display:none;">';
while($rowmodule = mysqli_fetch_array($result_module)){
$modid=$rowmodule['Id'];
$modname=$rowmodule['Name'];
$modearray[]=$modname;
foreach($modearray as $val){
//module name
echo '<li style="list-style-type:none;"><input type="checkbox" value="'.$modid.'"> '.$rowmodule['Name'].' </li>';
//fetch module permission for each module
$sql_modhooks="SELECT * FROM Module_hooks where Status='Active' and ModuleID='$modid'";
$result_modhooks = mysqli_query($link,$sql_modhooks);
echo '<ul style="display:none;">';
while($row_modhooks = mysqli_fetch_array($result_modhooks)){
echo '<li style="list-style-type:none;"><input type="checkbox" value="'.$modid.'"> '.$row_modhooks['display_txt'].' </li>';
}
echo '</ul>';
}
}
echo '</ul>';
}
}
echo '</ul>';
}else{
echo 'No Concern Added Yet! Pls Add a Concer First';
}
?>
It is giving me Output like this https://imgur.com/a/xlTMB0l, Result is coming as expected. Only problem value from first foreach loop duplicating as growing. what's wrong in the code
CodePudding user response:
$namearray[]=$name;
This appends to the existing array. Do unset($namearray)
before this statement and it should remove your duplicates I feel.