传递给codeigniter查看

时间:2012-01-23 19:02:57

标签: sql database codeigniter view

我正在尝试计算符合特定条件的表格行数。我的代码工作正常,并相应地返回行数。但我有问题在我的视图中回显那些行

我的控制员:

function index(){
  $data['states'] = $this->state_model->get_cities();
  $data['status'] = $this->state_model->get_status();

  $this->load->view('testviewad', $data);
}

在第2行中存储行数。如果我做了

<?php echo $status?>

在我看来它显示

  0
  0
  0
  0

但我应该展示

  0
  1
  3
  0

如果我从模型回显,则计算出的行数正确显示。所以我的查询工作正常。但我认为我在传递给观点时犯了错误。任何人都可以告诉我我做错了什么。

我的模特:

function get_status(){
  $states = $this->db->get('state');
  $like = array();

  foreach ($states->result() as $state){
    $cities = $this->db->get_where('city', array('state_id'=> $state->id));
    foreach ($cities->result() as $v){ 
      $s=$v->city_id."<br/>";
      $this->db->where('city_city_id',$v->city_id);
      $this->db->where('status_status_id',1);
      $q=$this->db->get('info');
      $sql =  $q->num_rows();  
    }
    return $sql;
  }
}   

我正在使用codeigniter。 提前致谢。

1 个答案:

答案 0 :(得分:2)

我的猜测是$data['status']每次迭代都会被覆盖,当0传递给视图时会保留$data['states'] = $this->state_model->get_cities(); $data['status'][] = $this->state_model->get_status(); // adding brackets - now $status will be an array 的值。

如果没有在“上下文中”看到相关代码,很难确切地说出来,但你可以这样做:

$status

然后你可以在视图中循环foreach ($status as $s) { echo $s . "\n"; }

$sql

<强>更新

审核更多代码后。您似乎在get_status()模型方法中覆盖了function get_status(){ $states = $this->db->get('state'); $like = array(); foreach ($states->result() as $state){ $cities = $this->db->get_where('city', array('state_id'=> $state->id)); foreach ($cities->result() as $v){ $s=$v->city_id."<br/>"; $this->db->where('city_city_id',$v->city_id); $this->db->where('status_status_id',1); $q=$this->db->get('info'); $sql[] = $q->num_rows(); // add the array brackets } } // move this down outside of the first foreach loop return $sql; // now $sql is an array of values } 。改为:

$data['status'] = $this->state_model->get_status();

然后,您对foreach ($status as $s) { echo $s . "\n"; } 的调用会返回一个数组,并且可以在视图中循环播放:

{{1}}