我在数据库中有两个表,我想以图像中所示的格式显示两个表中的数据。
表是
1 |标题1
2 |标题2
1 | test1 | 1
2 | test2 | 1
3 | test3 | 2
4 | test4 | 2
我使用foreach循环来显示table2的数据。
下面是我的代码。
$catgquestions=Array ( [0] => Array ( [id] => 1 [q_name] => test1 [table1_id] => 1 ) [1] => Array ( [id] => 2 [q_name] => test2 [table1_id] => 1 ) [2] => Array ( [id] => 3 [q_name] => test3 [table1_id] => 2 ) [3] => Array ( [id] => 4 [q_name] => test4 [table1_id] => 2 ) )
<?php foreach ($catgquestions as $catgquestionss) { ?>
<div class="form-group row">
<input type="hidden" id="catques" name="catques[]"
value=" <?php echo $catgquestionss['id']; ?>" >
<label for="catname" class="col-sm-4 col-form-label">
<?php echo $catgquestionss['q_name'];?>
</label>
</div>
<?php } ?>
但是我找不到解决方案来显示表1中的数据。
任何人都可以提供最佳解决方案吗?
预先感谢
答案 0 :(得分:1)
首先,您需要将表2与表1联接在一起,以获得这样的标题
SELECT t2.id,t2.q_name,t1.name FROM Table2 AS t2 INNER JOIN Table1 AS t1 ON t2.table1_id = t1.id ORDER BY t1.name ASC
注意:根据您的要求更改名称
您的结果将是这样
$catgquestions=Array ( [0] => Array ( [id] => 1 [q_name] => test1 [name] => Heading1 ) [1] => Array ( [id] => 2 [q_name] => test2 [name] => Heading1 ) [2] => Array ( [id] => 3 [q_name] => test3 [name] => Heading2 ) [3] => Array ( [id] => 4 [q_name] => test4 [name] => Heading2 ) )
因此,使用一个循环,您可以无需任何格式即可产生预期的输出
<?php
$heading = '';
foreach ($catgquestions as $catgquestionss) {
if ($catgquestionss['name'] != $heading) {
// your heading code here
echo $catgquestionss['name'];
$heading = $catgquestionss['name'];
}
// your exiting code here
echo $catgquestionss['q_name'];
}
?>
注意:请对代码进行必要的调整,但您将从此答案中获得一般想法。