如何从两个函数将数据传递到同一视图?

时间:2018-11-07 08:13:52

标签: php codeigniter

我有如下功能

public function view($slug = NULL){

        $data['book'] = $this->Book_Model->get_books($slug);
        $data['categories'] = $this->Category_Model->get_categories();

        //current book view
        $book_id = $data['book']['book_id'];
        echo "current book-".$data['book']['book_id']." ";

        if(empty($data['book'])) {
            show_404();
        }

        $this->add_views($book_id);
        $this->get_viewed_books($book_id);

        $this->load->view('templates/header', $data);
        $this->load->view('books/view', $data);
        $this->load->view('templates/footer');


    }

和我的 get_viewed_books 功能(如下所示)

public function get_viewed_books($book_id) {

$data['results'] = $this->Book_Model->get_viewed_books($book_id);

}

如何将$data['results']发送到$this->load->view('books/view', $data); 与来自第一个功能的其他数据?

1 个答案:

答案 0 :(得分:1)

get_viewed_books的结果分配给$data中的某个键:

$this->add_views($book_id);
$data['viewed_books'] = $this->get_viewed_books($book_id); // here

$this->load->view('templates/header', $data);
$this->load->view('books/view', $data);
$this->load->view('templates/footer');

现在,在模板中,您有一个viewed_books变量/键,可以对其进行迭代。

当然,您的get_viewed_books($book_id)应该返回结果,而不是将其分配给某个未知的$data变量:

public function get_viewed_books($book_id) {
    return $this->Book_Model->get_viewed_books($book_id);
}