0

CodeIgniter でこのコードを使用すると、注目のアイテムが 1 つだけ取得されます。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;
    }

私のコントローラー:

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>
4

1 に答える 1

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']
            );
        }
    }

このようにして、$data をクエリのすべての結果の配列として返します。再割り当てして 1 つの結果だけにするのではありません。

于 2011-02-25T17:24:23.527 に答える