Pass array from controller to view - Codeigniter

2019-02-27 13:09发布

I tried to print the array in the controller, before passing it to a view and this is the output

Array ( [annunci] => Array ( [0] => stdClass Object ( [EmailDatore] => you@welcom.it [Nome] => asdasd [Cognome] => asdas [IdAnnuncio] => 9 [Titolo] => sfsdfdsfshrea [Testo] => agrefdgdagdfg [Categoria] => [Sede] => [TipoContratto] => [Add_Date] => [Drop_Date] => ) 
[1] => stdClass Object ( [EmailDatore] => you@welcom.it [Nome] => asdasd [Cognome] => asdas [IdAnnuncio] => 10 [Titolo] => fafa [Testo] => fafaerea asdasdas dafasfd [Categoria] => [Sede] => [TipoContratto] => [Add_Date] => [Drop_Date] => ) ) )

I get the array from this method in my maincontroller

 public function get_annunci(){


    $query=$this->user_model->annunci($this->email);        
    print_r($query);        
    }

I would like to pass this array to a view and then read the data. So i rewrite my method like this

public function get_annunci(){
    $query=$this->user_model->annunci($this->email);        
    $this->load->view('main_view',$query);      
}

In main view i have this

<div class="tab-pane active" id="annunci">
    <ul>
        <?php
        print_r($annunci);
        ?>
    </ul>
</div>

This is my error

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: annunci

Filename: views/tab_annunci_view.php

Line Number: 4

4条回答
男人必须洒脱
2楼-- · 2019-02-27 13:29

(Change $query to $query ['annunci']) OK, the $query is an array already, then just change the view file to 'tab_annunci_view'

So:

public function get_annunci(){
    $query=$this->user_model->annunci($this->email);        
    $this->load->view('tab_annunci_view',$query);      
}
查看更多
Bombasti
3楼-- · 2019-02-27 13:32
public function get_annunci(){
    $query['annunci']=$this->user_model->annunci($this->email);        
    $this->load->view('main_view',$query);      
}

You're passing the array but you aren't passing annunci as a variable.

查看更多
我只想做你的唯一
4楼-- · 2019-02-27 13:42
public function index()
    {
        $data=$this->model->viewBlog();
        $this->load->view('blog/index',['data'=>$data]);
    }

I hope this is work. if you handle n number of records use this method.

查看更多
再贱就再见
5楼-- · 2019-02-27 13:49

This is because you have not defined $annunci and made it available to the view. You need to load it to the view first by

Controller

$data['id'] = $yourArray;
$this->load->view('your_view_file', $data);

View

 <?php print_r($id); ?> //prints $yourArray
查看更多
登录 后发表回答