我希望下面的代码将查询中的SQL信息与数组进行比较,以便即使在SQL中出现两次也不会回显相同的事情。
问题在于,有一件事会得到回声两次。我在每个循环中使用print_r
来查看数组如何变化,以及它是如何做的:
Array()
数组([0] => my_preset)
数组([0] => my_preset [1] => test_preset)
PHP代码:
$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>";
}
}
}
}
答案 0 :(得分:1)
问题是循环内部有foreach
填充数组,因此每次添加新预设时,您还会打印数组中包含的其余预设。只需将foreach
放在循环之后它就可以正常工作:
$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>";
}
}