2011-02-24 88 views
0

我在CodeIgniter中只使用此代碼獲取一個特色項目。我想獲得5個不同的特色項目。在CodeIgniter中加載數據

我的模型:

// GET THE FEATURED PRODUCTS 
    function getMainFeature(){ 
     $data = array(); 
     $this->db->select("id, a_title, a_description, a_image"); 
     $this->db->where('a_featured', true); 
     $this->db->where('a_status', 'active'); 
     $this->db->order_by("rand()"); 
     $this->db->limit(5); 

     $Q = $this->db->get('articles'); 

     if($Q->num_rows() >0){ 
      foreach($Q->result_array() as $row){ 
       $data = array(
        "id" => $row['id'], 
        "a_name" => $row['a_title'], 
        "a_description" => $row['a_description'], 
        "a_image" => $row['a_image'] 
       ); 
      } 
     } 
     $Q->free_result(); 
     return $data; 
    } 

我的控制器:

function index(){ 


    //get featured 
    $data['mainfeature'] = $this->MArticles->getMainFeature(); 
    $data['main'] = 'template/main/home'; 
    //load data and template 
    $this->load->vars($data); 
    $this->load->view('template/main/main_template'); 
} 

我的觀點:

<li> 
<?php 
foreach($mainfeature as $feat){ 

echo "<img src='".$mainfeature['a_image']."' border='0' align='left' width='320' height='320'/> \n"; 

} 
?> 
</li> 

回答

7

原因是這樣的......

if($Q->num_rows() >0){ 
     foreach($Q->result_array() as $row){ 
      $data = array(  //<-----------HERE 
       "id" => $row['id'], 
       "a_name" => $row['a_title'], 
       "a_description" => $row['a_description'], 
       "a_image" => $row['a_image'] 
      ); 
     } 
    } 

每次迭代循環時,您都覆蓋(重新分配)您的變量$data變量。

代替上述的,試試這個...

$data = array();  //declare an empty array as $data outside the loop 
    if($Q->num_rows() >0){ 
     foreach($Q->result_array() as $row){ 
      $data[] = array(   //using square brackets will push new elements onto the array $data 
       "id" => $row['id'], 
       "a_name" => $row['a_title'], 
       "a_description" => $row['a_description'], 
       "a_image" => $row['a_image'] 
      ); 
     } 
    } 

這樣,你將返回$數據查詢的所有結果的數組,而不是重新分配它,僅僅結束了只有一個結果。

相關問題