在CodeIgniter中加载数据

ktm*_*ktm 0 php arrays codeigniter codeigniter-2

我在CodeIgniter中只获得了一个带有此代码的特色项目.我想获得5种不同的特色商品.

我的模特:

    // 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;
    }
Run Code Online (Sandbox Code Playgroud)

我的控制器:

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');
}
Run Code Online (Sandbox Code Playgroud)

我的观点:

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

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

}
?>
</li>
Run Code Online (Sandbox Code Playgroud)

jon*_*ohn 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']
            );
        }
    }
Run Code Online (Sandbox Code Playgroud)

$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']
            );
        }
    }
Run Code Online (Sandbox Code Playgroud)

这样,您将返回$ data作为查询的所有结果的数组,而不是重新分配它,并且只以单个结果结束.