Codeigniter,如何在foreach内部查询存储值

时间:2013-02-26 06:40:31

标签: php sql codeigniter

我有这样的代码

$this->load->model("m_crud");
$test= $this->m_crud->get_querry; //this model already have query and result() to return
foreach($test as $retest)
   {
    echo $retest->primary_id;
    $test2=$this->db->query("select * from table2 where id='$retest");
    foreach($test2 as $retest2)
       {
         echo $retest2->name;
        }
   }

很容易将所有这些代码放到“视图”,但我想使用MCV模型。 我尝试使用如下数组存储结果:

$data['test']=$test
foreach($test as $retest)
   {
    echo $retest->primary_id;
    $test2=$this->db->query("select * from table2 where id='$retest");
    $data['test2']=$test2
    foreach($test2 as $retest2)
       {
         echo $retest2->name;
        }
   }
$this->load->view("test_view",$data);

我在视图中得到的是$test2的回声中的值相同,每个$test

的回声应该不同 谢谢你,抱歉我的英文不好

2 个答案:

答案 0 :(得分:0)

这是一个简单的例子

控制器方法

function getResult()
{
    $this->load->model('mymodel');
    $results    =   $this->mymodel->getRecords();
    $data['results']    =   $results;
    $this->load->view('myview',$data);
}

模型方法

function getRecords()
{
    return $this->db->query("select * from table2 where id='$retest")->result_array();
}

并查看

foreach($results as $row){
    echo $row['id'];
    echo '<br>';
    echo $row['othercolumn'];
}

答案 1 :(得分:0)

您可以在视图页面中使用

foreach($test2 as $newarray)
{
     foreach($newarray->result() as $row)
     {
           echo $row->columnnames;//
     }
}