开发者

Passing multiple variables to a view?

so,i have two variables $posts and $comments that holds the array of posts and comments respectively,i have a separate view that accepts these variables,executes a foreach loop and prints them on the same page. The question here is,how d开发者_如何学Goo i pass both the variables to a view?

If its a single variable i pass it like this $this->load->view('myview',$myvar).

I tried passing it as an array like this,but still it doesnt work.

$data=array($var1,$var2);
$this->load->view('myview',$data);

Any help would be greatly appreciated! Thanks.


You need to access the variable in your view as you pass it. Using array($var1,$var2); is valid but probably not what you wanted to achieve.

Try

$data = $var1 + $var2;

or

$data = array_merge($var1, $var2);

instead. See Views for detailed documentation how to access variables passed to a view.

The problem with using array($var1,$var2); is that you will create two view variables: ${0} and ${1} (the array's keys become the variable names, you have two keys in your array: 0 and 1).

Those variable names are invalid labels so you need to enclose the name with {} on the view level.

By that you loose the ability to name the variables usefully.


The easiest thing to do in your controller:

$data['posts'] = $posts;
$data['comments'] = $comments;
$this->load->view('your_view', $data);

Then, in your view you just simply do something like:

foreach($posts as $post) {
...
}

You can hold any object in the $data variable that you pass to your view. When I need to traverse through result sets that I get from my models I do it that way.


Using associative array looks the best possible solution. take an array

$data = array(
    'posts' => $posts,
    'comments' => $comments,
);
$this->load->view('myview',$data);

Probably this will help you to get a solution.


this is another and recommended way using compact:

$data1 = 'your data';
$data2 = 123;
$data3 = array();

$this->load->view('myview', compact('data1', 'data2', 'data3');


try

 $data1 = 'your data';
$data2 = 123;
$data3 = array();

$this->load->view('myview', $data1 + $data2 + $data3);


$this->render($views_array,$data);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜