Reputation: 17616
Checked to see if this is a duplicate, it would appear so but the other questions I've found do not answer this question.
I'm using CodeIgniter and I would like to access a 'complex' array (from a db) in my view.
Codeigniter passing data from controller to view The link answers part of my question, but it's a simple array like so:
In the controller:
$data = array(
'title' => 'title 1',
'user' => 'user 1'
);
$this->layout->view('example/test', $data);
In the view
echo $title.$user;
So all of that I do get, however what if the array was a little more complicated like:
$data = array(
array(
'title' => 'title 1',
'user' => 'user 1'
),
array(
'title' => 'title 2',
'user' => 'user 2'
)
);
How can I access this kind of array in my view?
Upvotes: 1
Views: 209
Reputation: 1549
You can simply try this:
$data['content'] = array(
array(
'title' => 'title 1',
'user' => 'user 1'
),
array(
'title' => 'title 2',
' user' => 'user 2'
)
);
$this->load->view('example/test',$data);
In View:
foreach($content as $value)://to traverse the data array ....
endforeach;
Upvotes: 1
Reputation: 883
Use this in controller :
$data = array(
array(
'title' => 'title 1',
'user' => 'user 1'
),
array(
'title' => 'title 2',
'user' => 'user 2'
)
);
$content = array('data'=> $data);
$this->layout->view('example/test', $data);
In view file :
foreach($data as $key=>$val)
{
echo $val['title'].$val['user'];
}
Upvotes: 2
Reputation: 1625
you should wrap the outer array and give it a key like this
$data = array(
'myAwesomeArray' => array(
array(
'title' => 'title 1',
'user' => 'user 1'
),
array(
'title' => 'title 2',
'user' => 'user 2'
)
)
);
you should be able to access your data in the view using $myAwesomeArray
Upvotes: 2