Passing 2 types of array variables in codeigniter

2019-04-01 22:08发布

问题:

If i have $data[] array and $another_data[] in controller how do we pass both type of data in view files ? provided that codeigniter implementation is like $this->load->view('view_page', $data)

回答1:

If you can guarantee that the array keys are unique across the two arrays you can use array_merge to merge the two arrays before passing to the view.

$this->load->view('view_page', array_merge($data, $another_data));

Otherwise you can create a parent array and store both as subarrays.

$parent_data = array('data' => $data, 'another_data' => $another_data);
$this->load->view('view_page', $parent_data);


回答2:

Try this:

$data['array1'] = $array1;
$data['array2'] = $array2;
this->load->view('view_page', $data);

Then in your view, access the two arrays as $array1 and $array2.



回答3:

Just assign them as child arrays of the array you are passing to the view. I always create a $view_data array in the controller, and then despatch this to the view using $this->load->view('layout', $view_data);

Here is some example of what I mean:

$view_data['page_title'] = 'Array Examples';
$view_data['view_file'] = 'examples/array';
$view_data['array_one'] = array('apples', 'bananas', 'pears');
$view_data['array_two'] = array('ford', 'skoda', 'peugeot');
$this->load->view('layout', $view_data);

Then in the view you can access them like the following:

<h6>List of fruits:</h6>
<pre><?php print_r($array_one); ?></pre>

<h6>List of cars:</h6>
<pre><?php print_r($array_two); ?></pre>

Hope that helps.



回答4:

$this->load->view("first"=>demo, "second"=>demo2);

foreach( $first->array_result()  as $result )
{
    $result['test'];
}

foreach( $second->array_result()  as $result )
{
    $result['test'];
}


标签: codeigniter