在我的数据库中,我有2个表。
轴表:
______________________________________
| axle_id | train_id | axle | distance |
|_________|__________|______|__________|
| 1 | 1 | 1 | 20 |
| 2 | 1 | 2 | 50 |
| 3 | 1 | 3 | 200 |
| 4 | 1 | 4 | 50 |
| 5 | 1 | 5 | 200 |
| 6 | 1 | 6 | 50 |
| 7 | 1 | 7 | 200 |
| 8 | 1 | 8 | 50 |
|_________|__________|______|__________|
转向架表:
___________________________________________
| bogie_id | axle_id | train_id | bogie_nr |
|__________|_________|__________|__________|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 1 | 1 |
| 3 | 3 | 1 | 2 |
| 4 | 4 | 1 | 2 |
| 5 | 5 | 1 | 3 |
| 6 | 6 | 1 | 3 |
| 7 | 7 | 1 | 4 |
| 8 | 8 | 1 | 4 |
|__________|_________|__________|__________|
现在我想在我的页面上显示这些结果:
_____________________
| bogie_nr | axle |
|__________|_________|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 3 | 5 |
| 3 | 6 |
| 4 | 7 |
| 4 | 8 |
|__________|_________|
我尝试使用此代码执行此操作:
<table id="end_result_axle_bogies">
<tr>
<th>Train Axles</th>
<th>Train Bogies</th>
</tr>
<!--Show the end result!-->
<?php
$show_end_table = $database->axles($_GET['train_id']);
$show_end_table2 = $database->bogies($_GET['train_id']);
foreach($show_end_table as $end_axle_table){
echo "<tr>" . "<td>" . $end_axle_table['axle'] . "</td>";
}
foreach($show_end_table2 as $end_axle_table2){
echo "<td>" . $end_axle_table2['bogie_nr'] . "</td>" . "</tr>";
}
?>
</table>
输出有效(向我显示正确的信息)。但是这张桌子效果不好。它向我展示了这个结果:
(将文字设为绿色以查看div是否正常工作。确实如此。)
有人知道如何使表正常工作吗?
答案 0 :(得分:1)
试试这个:
<?php
$show_end_table = $database->axles($_GET['train_id']);
$show_end_table2 = $database->bogies($_GET['train_id']);
$table2 = "";
foreach($show_end_table2 as $end_axle_table2){
$table2[] = $end_axle_table2['bogie_nr'];
}
foreach($show_end_table as $key => $end_axle_table){
echo "<tr>";
echo "<td>" . $end_axle_table['axle'] . "</td>";
echo "<td>" . $table2[$key] . "</td>";
echo "</tr>";
}
?>
改变foreach。就像你现在一样,它是<tr><td>1</td><tr><td>2</td>
...在一个foreach中回声是更好的方法。
答案 1 :(得分:0)
可能是以下代码适合您....
<table id="end_result_axle_bogies">
<tr>
<th>Train Axles</th>
<th>Train Bogies</th>
</tr>
<!--Show the end result!-->
<?php
$show_end_table = $database->axles($_GET['train_id']);
$show_end_table2 = $database->bogies($_GET['train_id']);
foreach($show_end_table as $end_axle_table){
echo "<tr>" . "<td>" . $end_axle_table['axle'] . "</td>";
}
</table>
<table>
foreach($show_end_table2 as $end_axle_table2){
echo "<tr><td>" . $end_axle_table2['bogie_nr'] . "</td>" . "</tr>";
}
?>
</table>
答案 2 :(得分:0)
试试这个:
从转向架表中取出所有bogie_nr和相应的axle_id 然后像
那样制作循环foreach(bogie_nr as bogie)
<tr>
<td> show bogie_nr </td>
<td> Fetch axle for respective axle_id of bogie_nr from axle table
</td>
</tr>
end for loop
</tr>
答案 3 :(得分:0)
您可以尝试使用MySQL视图(info here),然后在foreach循环中循环遍历1视图,而不是进行2次数据库调用。