Welcome Guest, Not a member yet? Register   Sign In
passing an array to a view
#1

[eluser]obay[/eluser]
Hi,

I am very new to CI, and I found out that when arrays are passed to views, the keys are converted to variables.

But I needed to pass an array to my view. So currently, this is my controller:

Code:
$user_levels = $this->User_model->get_user_levels();
$this->load->view('user_create_view', array("user_levels" => $user_levels));

and my view:

Code:
User Level: <?=form_dropdown("level",$user_levels);?>

and it works. (By the way, $user_levels in my controller is an array)

I was just wondering if there was a better way to do this, as creating a new array to wrap my existing array $user_levels seemed,.. uhh.. redundant...

Any ideas?

Thanks
#2

[eluser]kgill[/eluser]
Nope that's the way it's done, if it's any consolation eventually you'll likely be sending more than just user_levels to your view when you're done so the whole array within an array won't be so bad.
#3

[eluser]jedd[/eluser]
Hi obay,

Convention tends to be that you send $data to your view .. not enforced or required of course, but you'll often see people using it to wrap up other variables, including arrays, with the same intent that you have here.

So instead of what you're currently doing:

Quote:
Code:
$user_levels = $this->User_model->get_user_levels();
$this->load->view('user_create_view', array("user_levels" => $user_levels));

... you could instead just do this:

Code:
$data['user_levels'] = $this->User_model->get_user_levels();
$this->load->view('user_create_view', $data);

It means that anything else you want to use while in your user_create_view can just be whanged into a $data['xyz'] construct the same way.




Theme © iAndrew 2016 - Forum software by © MyBB