0

我有两个表,它们是连接的,每个表的 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

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

4

1 回答 1

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>';
于 2013-05-24T16:58:57.040 回答