0

我有两个查询 $q1 和 $q2。从query1我得到多条记录,每条记录都有id,我想在where条件下使用这个id进行第二次查询。

我在控制器中这样做。我试过以下代码。在 foreach 中,我试图存储 id 并传递给 $q2 where 条件。

//Query 1
    $q1 = $this->db->select(array(
                                 'spf.id as id' ,
                                  'spf.name',
                                'spf.added_on'
                                ))->from('sp_form spf')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
                   $data['data'] = $q1->result_array();

                foreach($data as $rec)
                {
                   $id = $rec['id']; // here how i catch id for each row

                 //Query 2

                    $q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')->where('spft.formid',$id)->get();
                      $data['count'] =  $q1->row_object();
                }
                // pass combine result to view

                 $this->load->view('myview', $data,true);

编辑:

This is my view.

I have try Nishant answer and i get resultq1 using foreach but how can i get result of resultq2.


    <table width="100%">
      <tr>
        <td class="th"> Details</td>
        <td width="5%" class="th"> Answer</td>
        <td width="15%" class="th">Started by</td>
        <td  width="15%" class="th">Created on</td>
      </tr>
      <?php foreach($resultq1 as $row):?>
       <tr>
        <td><?php echo $row['name'] ;?></td>

         <td >---- </td> // here i want to use resultq2

         <td><?php echo $row['added_by'] ;?></td>
        <td ><?php echo $row['added_on'];?></td>
      </tr>
      <?php endforeach;?>
    </table>
4

2 回答 2

0

你可以这样做。

$resultq1= $q1->result_array();
$data['resultq1'] = $resultq1;

$resultq2 = array();$i=0;
foreach($resultq1 as $row){
   $id = $row['id'];
   $q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')>where('spft.formid',$id)->get();
   $resultq2[$i]['count'] =  $q1->row_object();
   $i++; 
}
$data['resultq2'] = $resultq2;
$this->load->view('myview', $data,true);

或者

您可以使用 array_merge

喜欢

$data = array_merge($resultq1, $resultq2);

然后在 myview 中,您将在变量 $resultq1 和 $resultq2 中获得结果。

您可以通过 $data['variable_name'] 将任意数量的变量从控制器传递到视图文件,并且可以像简单变量 $variable_name 一样在视图文件中检索它。

一些可能有帮助的示例链接:- 在 codeigniter 视图文件中传递 2 种类型的数组变量

于 2013-02-28T11:26:18.453 回答
0
$data['count'] =  $q1->row_object();

更改如下:

foreach($data as $rec)
       {
          $id = $rec['id']; // here how i catch id for each row
          $q2 = $this->db->select("count('id') as count ")->
          from('sp_topic spft')->where('spft.formid',$id)->get();
          $data[$id]['count'] =  $q2->result_array();
       }

$this->load->view('myview', $data,true);
于 2013-02-28T11:29:43.227 回答