【问题标题】:Loading data in CodeIgniter在 CodeIgniter 中加载数据
【发布时间】:2011-02-24 10:06:28
【问题描述】:

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

我的控制器:

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>

【问题讨论】:

    标签: php arrays codeigniter codeigniter-2


    【解决方案1】:

    原因是这样的……

        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 作为查询的所有结果的数组,而不是重新分配它并仅以单个结果结束。

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 2018-06-07
      • 2013-01-13
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      相关资源
      最近更新 更多