kockburn
kockburn

Reputation: 17616

Codeigniter passing data from controller to view /w complex arrays

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

Answers (3)

saurabh kamble
saurabh kamble

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

Suman Biswas
Suman Biswas

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

Mateo Torres
Mateo Torres

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

Related Questions