Foreach循环里面有两个查询

时间:2016-06-13 06:49:58

标签: php mysql foreach

我有两个查询工作正常,每个查询将检索3行。我试图在foreach循环中使用带有两(2)个查询的foreach在表上显示查询结果。我尝试将两个result()放在foreach上,但它是一个错误。如何在单个foreach循环中显示两个result()?我不知道如何实现这一点。

查询1将在列“投资者名称”上,然后查询2将在“金额”上。

以下是代码:

<?php

    $query5 = $this->db->query("SELECT * FROM ".tbl_investors." WHERE id IN (SELECT MAX(investor_id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");

    $query6 = $this->db->query("SELECT * FROM ".tbl_investors_ledger." WHERE id IN (SELECT MAX(id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");

?>

                    <table class="table table-striped table-bordered table-hover" id="dataTables">
                        <thead>
                            <tr>  
                                <td>Investor Name</td>
                                <td>Amount</td>
                          </tr>
                        </thead>
                        <tbody style="text-align: center;">

                                <?php
                                foreach ($query5->result() as $row) && ($query6->result() as $row2){
                                ?>
                                <tr>
                                    <td><?php echo $row->last_name.', '.$row->first_name; ?></td>
                                    <td><?php echo $row2->amount; ?></td>
                                </tr>
                                <?php } ?>

                        </tbody>
                    </table>

2 个答案:

答案 0 :(得分:0)

据我所知,foreach循环只能处理一个查询。我看到了两个选项,真的..

选项1

创建两个不同的foreach循环,不在彼此内部,因为这会产生双重结果,但在彼此之外。这可能不会做你想要的,但它可能值得一试,如下:

<!-- FIRST LOOP -->

<?php 
foreach ($query5->result() as $row) {
?>

  <td> Your data goes here </td>

<?php 
}
?>

<!-- SECOND LOOP -->

<?php 
foreach ($query6->result() as $row) {
?>

  <td> Your data goes here </td>

<?php 
}
?>

选项2

通过使用&#34; JOIN&#34;

,只创建一个查询,只需要一个循环

请参阅this post

上的回答

答案 1 :(得分:0)

您不能在foreach循环上使用两个array_expressions。最好在查询中使用join来使其成为一个。

之类的东西
$query = "SELECT `tbl_investors`.* , `tbl_investors_ledger`.*  
 FROM `tbl_investors` 
 LEFT JOIN  `tbl_investors_ledger` 
 ON `tbl_investors`.id = `tbl_investors_ledger`. investor_id 
 WHERE `tbl_investors`.deleted = 0 AND `tbl_investors_ledger`.deleted = 0 
 GROUP BY `tbl_investors_ledger`.investor_id 
 ORDER BY `tbl_investors_ledger`.id DESC ";