簡體   English   中英

從數組結果循環查詢

[英]looping query from array result

我在 MODEL 中有查詢,從 table1 中選擇包含以下數據的數據:

Column NOPE

數據1
數據2
數據3

然后我想從 table1 的結果中選擇所有數據,但只獲取第一行:

不| 總計
nope1 | 20人

如何循環所有行以在我的 VIEW 中選擇和顯示所有行? 所以我從這樣的選擇中獲得所有行:NOPE TOTAL
nope1 20人
nope2 30人
nope3 25人
nope4 40人

這是我的模型:

function test()
{
$query = $this->db->query("select nope from tb1");

if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
    {

        $nopen=$row['nope'];
        $query2=$this->dbmssql->query("
                                        select nope, 
                                        count(name) as total 
                                        from trans 
                                        where nope ='$nopen' 
                                        and date='2016-04-20'
                                        group by nope ");
        return $query2->result_array();

    }

}       

}

我的觀點是:

                    <tbody> 
                <?php 
                $no=0;
                foreach ($res as $row) { $no++?>                    
                <tr>
                    <td><?php echo $no;?></td>
                    <td><?php echo $row['nope'] ;?></td>
                    <td><?php echo $row['total'];?> PAX</td>
                </tr>       
                <?php 
                } ?>    
                </tbody>

請幫助我,非常感謝。

您只能獲得第一行,因為您的 foreach 循環只執行一次,因為循環在 return 語句處退出。 您需要將結果數組分配給一個變量並在循環后返回該變量。

這是您修改后的代碼,用於對 $query 中的每條記錄執行 foreach 循環。

function test()
{
   $query = $this->db->query("select nope from tb1");

   if ($query->num_rows() > 0)
   {
      foreach ($query->result_array() as $row)
      {

        $nopen=$row['nope'];
        $query2=$this->dbmssql->query("
                                    select nope, 
                                    count(name) as total 
                                    from trans 
                                    where nope ='$nopen' 
                                    and date='2016-04-20'
                                    group by nope ");
          $all_records[]=$query2->result_array();

       }
       return $all_records;
  }       

}

數百萬感謝您,Salain 先生....

最后,我已經按照您的代碼進行操作,並使用以下命令更改我的 VIEW:

                    <?php 
                $no=0;

                foreach ($res as $row) 
                { 
                $no++;
                ?>                  
                <tr>
                    <td><?php echo $no;?></td>
                    <td><?php echo $row[0]['nope'] ;?></td>
                    <td><?php echo $row[0]['total'];?> PAX</td>
                </tr>       
                <?php

                } ?>

現在我得到了所有記錄的結果,..你是我的英雄......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM