foreach循环不会从控制器打印视图页面中的所有值

时间:2012-02-24 05:30:30

标签: php codeigniter-2

  

如何使用foreach loop.i使用循环但是它来打印所有值   只打印数组值的最后一个值。

query=$this->Common_model->getTableData('table name', array('field name' => $param))->result();


     foreach($query as $rows)
     {

     $user=$rows->userby;
     $data['user_status']=$rows->status;

      $data['user']=$user;

      $status=$this->Common_model->getTableData('table name', array('id' =>$data['user_status']))->row();

      $data['status']=$status->name;


     }

2 个答案:

答案 0 :(得分:1)

应该是:

$query=$this->Common_model->getTableData('table name', array('field name' => $param));  //remove ->results()


     foreach($query->result() as $rows)  // correction here.
     {

     $user=$rows->userby;
     $data['user_status']=$rows->status;

      $data['user']=$user;

      $status=$this->Common_model->getTableData('table name', array('id' =>$data['user_status']))->row();

      $data['status']=$status->name;


     }

每次调用result()函数,逐行遍历行(按顺序)。

答案 1 :(得分:1)

您只获取最后一个值的原因是您将值分配给覆盖先前值的相同索引。你应该试试这个

foreach($query->result() as $rows)  // correction here.
     {

     $user=$rows->userby;
     $data['user_status'][]=$rows->status;

      $data['user'][]=$user;

      $status=$this->Common_model->getTableData('table name', array('id' =>$data['user_status']))->row();

      $data['status'][]=$status->name;


     }