我有两个表,它们是联接在一起的,并且每个表和下面的元素的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


我想列出相关元素的类别名称和子ID。几个ObjectName将具有几个相关的类。

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


在每个字段下应该列出更多的值。

最佳答案

看来您需要稍微简化代码。我的猜测是由于每个结果集中的行数不同,所以出现了问题。即使较大的集中还有更多元素,这也会使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>';

10-07 14:18