2011-02-24 4 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'] 
      ); 
     } 
    } 
,536,

루프를 반복 할 때마다 변수 $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'] 
      ); 
     } 
    } 

이 방법 대신에, 쿼리의 모든 결과의 배열로 $ 데이터를 반환됩니다를 재 할당 만 결말 단일 결과.

관련 문제