2012-01-23 72 views
0

我正在嘗試計算符合特定條件的表的行數。我的代碼工作正常,並相應地返回行數。但我有問題呼應行的數量我認爲傳遞到codeigniter中查看

我的控制器:

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; 
    } 
} 

我用笨。 在此先感謝。

+0

首先,它是編寫有效的PHP一個很好的做法。也就是說,不要'<?php echo $ status?>',而是'<?php echt $ status; ?>'。從控制器直接回顯時,你會得到什麼?它仍然是'0 0 0 0'還是'0 3 1 0'? – 2012-01-23 19:12:21

+0

如果從模型回顯,例如,如果我確實echo $ sql它顯示正確的答案。 – user1052462

+0

將你的'return $ sql;'向上移動一行,在'}' – Anil

回答

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"; 
} 

UPDATE

在審查更多的代碼後。看來你在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->state_model->get_status();調用返回一個數組,可以通過在視圖中循環:

所有的
foreach ($status as $s) 
{ 
    echo $s . "\n"; 
} 
+0

之前顯示0,0,0,0,0與我的輸出相同:( – user1052462

+0

你能顯示更多的控制器嗎?整個循環會幫助你 - 因爲這就是我認爲我們遇到問題的地方,而且,更多的視圖背景將會有幫助, – swatkins

+0

我的完整控制器和模型如上所示 – user1052462