我有两个表,它们是连接的,每个表的ID和下面的元素是相似的。
parentID | objectName | subID ID| className| subName |
_____________________________ ________________________
84 | Test | 14 14| BOM | Test
84 | More | 16 14| PDF | Test
84 | Sub | 15 15| Schematics | Test2
我想列出相关元素的categoryname和subID。几个ObjectNames将有几个相关的类。
PHP代码:
$objects = mysqli_query($con,"SELECT * from subobject");
$join = mysqli_query($con, "SELECT * FROM subrelation AS subrelation INNER JOIN subobject AS subobject ON subobject.subId = subrelation.ID;");
echo "<ul>";
while($obj = mysqli_fetch_array($objects) and $row = mysqli_fetch_array($join))
{
echo "<li>". $obj['objectName'];
echo "<ul>";
//ITERATION GOES HERE
if($obj['objectName'] == $row['subName'])
echo "<li>". "$row[className]" . "</li>";
//END OF ITTERATION
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>
和输出列表:
-Test
-BOM
-Sub
-Schematics
-More
在每个字段下面应该有更多列出的值。
答案 0 :(得分:1)
看起来您需要稍微简化一下代码。我的猜测是你的问题正在发生,因为你在每个结果集中有不同的行数。这使得while
循环在完成较小的结果集(可能是$objects
)时退出,即使较大的集合中还有更多元素。
解决方案是对查询结果进行排序,在while
循环中只使用一个条件,并使用字符串objectName
跟踪您当前使用的$curr_objectName
个$join = mysqli_query($con, 'SELECT * FROM subrelation AS subrelation INNER JOIN subobject AS subobject ON subobject.subId = subrelation.ID ORDER BY subobject.objectName;');
$curr_objectName = '';
echo '<ul>';
while($row = mysqli_fetch_array($join)) {
$subName = $row['subName'];
if($subName != $curr_objectName)) {
if($curr_objectName != '') {
#close the previous list
#will be skipped on the first loop iteration
echo '</ul>';
echo '</li>';
}
#start a new list
$curr_objectName = $subName;
echo '<li>'. $obj['objectName'];
echo '<ul>';
} else {
echo '<li>'. $row['className'] . '</li>';
}
}
echo '</ul>';
:
{{1}}