Codeigniter trouble passing array to view

2019-08-21 07:22发布

问题:

I am trying to pass an array and use it in my view from my controller but instead i am getting some errors...

In my Controller:

$data = array(
  'a' => 'b',
  'c' => 'd'
);
$this->load->view('home/index', $data);

In my View:

print_r($data);

throws errors and doesnt allow me to print it, since i am trying to then pass the array to another view for my app.

Error:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: home/index.php

Line Number: 1

回答1:

Codeigniter will create variables named with the keys of every item in your data array.

If you want them all in one data array accessible in your view, try that:

$data = array(
  'data' => array(
       'a' => 'b',
       'c' => 'd'
  ) 
);


回答2:

In the view, try accessing as $a and $c rather than $data



回答3:

$data is just a variable and has nothing to do with the names of variables accessible by the view.

you won't use $data, will use $a and $c because they are the keys of your array values.

Take a look at Codeigniter documentation.