【问题标题】:passing to view in codeigniter在 codeigniter 中传递给视图
【发布时间】:2012-01-23 19:02:57
【问题描述】:

我正在尝试计算我的表格中满足特定条件的行数。我的代码工作正常并相应地返回行数。但我无法在我的视图中回显该行数

我的控制器:

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

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

在第二行存储了行数。如果我这样做了

<?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。 提前致谢。

【问题讨论】:

  • 首先,编写有效的 PHP 是一个好习惯。也就是说,不要&lt;?php echo $status?&gt;,而是&lt;?php echt $status; ?&gt;。直接从控制器回显时会得到什么?还是0 0 0 0还是0 3 1 0
  • 如果从模型中回显,例如,如果我回显 $sql,它会显示正确的答案。
  • return $sql; 上移一行,在} 之前

标签: sql database codeigniter view


【解决方案1】:

我的猜测是,$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";
}

更新

查看更多代码后。您似乎在 get_status() 模型方法中覆盖了 $sql。将其更改为:

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-&gt;state_model-&gt;get_status(); 的调用会返回一个数组,并且可以在视图中循环:

foreach ($status as $s) 
{
    echo $s . "\n";
}

【讨论】:

  • 你能展示更多你的控制器吗?整个循环会有所帮助——因为我认为这就是我们遇到问题的地方。此外,更多的视图上下文会有所帮助。
  • 上面给出了我的完整控制器和模型。
  • 哦,好的。您正在循环中覆盖$sql。我会更新我的答案。
  • @swatkins..thanks 但有一点问题,它只给出输出 3 3 3 3。但它应该给出 3 0 2 0 :(
  • 我已将return $sql 命令移到循环之外。它是在循环内返回的——这可能是问题所在。
猜你喜欢
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多