im using array for open a file, if value match in array key, then will open file that related with value. when i try, it will open file as much as data in database.
while ($d = mysqli_fetch_array($query)) { $d['grade'] = array("2", "3", "4", "5", "6"); if(in_array("2", $d)) { include "table/grade2_tab.php"; } if(in_array("3", $d)) { include "table/grade3_tab.php"; } if(in_array("4", $d)) { include "table/grade4_tab.php"; } if(in_array("5", $d)) { include "table/grade5_tab.php"; } if(in_array("6", $d)) { include "table/grade6_tab.php"; } } ?>
lets say i have 6 data in database, like :
=>grade6 =>grade6 =>grade6 =>grade6 =>grade3 =>grade2
If data already found in array then just open once file for each key. how to achieve this ? i try using if but data for grade6
open four times.
i don’t know how to get deal with this, i search for groupping data with foreach but i don’t know to open a file with foreach. any answer is appreciated.
Advertisement
Answer
Create another array to hold the values you’ve already used, and you can also simplify your code a lot using a loop.
$grades = array("2", "3", "4", "5", "6"); //create an empty array to hold grades once they are displayed $used = []; while ($d = mysqli_fetch_array($query)) { //loop through each grade value foreach($grades as $grade) { //check if `$grade` is in array `$d` //AND check if `$used[$grade]` has not been set (if it hasn't been set, it hasn't been displayed) if(in_array($grade, $d) && !isset($used[$grade])) { //set $used[$grade] so the previous check will fail if this grade is a duplicate $used[$grade] = true; //include your php file include "table/grade{$grade}_tab.php"; } } }
This solution means you no longer have to add an IF block for each grade.