gpt4 book ai didi

php - 迭代表中的列表值

转载 作者:行者123 更新时间:2023-11-29 13:50:33 24 4
gpt4 key购买 nike

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

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

最佳答案

看来您需要稍微简化一下代码。我的猜测是,您出现问题是因为每个结果集中的行数不同。这使得您的 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>';

关于php - 迭代表中的列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16740016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com