Reputation: 117
I want the code below to compare SQL-information from query with a array, in order to not echo same thing twice even though it appear two times in the SQL.
The problem is that one thing gets echo two times. I use print_r
in every loop to see how the array changes, and here is how it does along:
Array ( )
Array ( [0] => my_preset )
Array ( [0] => my_preset [1] => test_preset )
The PHP code:
$parentArray = array();
$sql = "SELECT * FROM wb_values";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
print_r($parentArray);
if (!in_array($row['parentID'], $parentArray)) {
array_push($parentArray, $row['parentID']);
foreach ($parentArray as $parent) {
$sqlParent = "SELECT * FROM presets WHERE id='$parent'";
$resultParent = mysqli_query($conn, $sqlParent);
while ($row = $resultParent->fetch_assoc()) {
echo "<div class='section'>
<div class='left-mark'></div>
<p class='text'> ".$row['preset_name']." </p>
</div>";
}
}
}
}
Upvotes: 0
Views: 45
Reputation: 2670
The problem is that you have the foreach
inside the loop that fills the array, so each time a new preset is added you print also the rest of presets included in the array. Just put the foreach
after the loop and it should work fine:
$parentArray = array();
$sql = "SELECT * FROM wb_values";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
print_r($parentArray);
if (!in_array($row['parentID'], $parentArray)) {
array_push($parentArray, $row['parentID']);
}
}
foreach ($parentArray as $parent) {
$sqlParent = "SELECT * FROM presets WHERE id='$parent'";
$resultParent = mysqli_query($conn, $sqlParent);
while ($row = $resultParent->fetch_assoc()) {
echo "<div class='section'>
<div class='left-mark'></div>
<p class='text'> ".$row['preset_name']." </p>
</div>";
}
}
Upvotes: 1