'Send multiple array to view in codeigniter
I have two arrays, first is an array with its data is declared on controller and the second is an array from a query operation. Both of them are not related to other. Lets name them $array1 and $array2. Below is my controller
$array1['status'] = 'admin';
$array1['name'] = 'John';
$this->load->model('mymodel');
$array2 = $this->mymodel->get_all_row();
$this->load->view('my_view', $array1, $array2);
Lets say the $array2 have 3 indexes id, name, price.
Need some helps.
Solution 1:[1]
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. See Views for detailed documentation how to access variables passed to a view.
Try
$data = $var1 + $var2;
or
$data = array_merge($var1, $var2);
Solution 2:[2]
The view accepts only two parameters.
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Third Parameter of View
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to TRUE (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned:
$string = $this->load->view('myfile', '', TRUE);
So, bottom line is that you have to send one array. Now if you wanna pass data of two array, you should merge these arrays into and then pass merged array.
$merged_array = array_merge($array1, $array2);
$this->load->view('my_view', $merged_array);
Solution 3:[3]
When you want to pass two arrays to your view, you need to convert the data array to a two-dimensional array. For example, you have two arrays with the following names and contents:
[A1] => Array
(
[ID] => '1'
[Name] => 'Jon'
)
[A2] => Array
(
[Tell] => '123456'
[Address] => 'Somware'
)
To pass two arrays, place them in the data array with different keys
$data['A1']=$A1;
$data['A2']=$A2;
Result:
[data] => Array
(
[A1] => Array
(
[ID] => '1'
[Name] => 'Jon'
)
[A2] => Array
(
[Tell] => '123456'
[Address] => 'Somware'
)
)
and use in view like this:
echo $A1['ID'];
echo $A1['Name'];
echo $A2['Tell'];
echo $A2['Address'];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quan Lee |
| Solution 2 | |
| Solution 3 | Sina Said |
