1

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?

1
  • 1
    you have passed $data in view method.. this is not actual array, this array all alphanumeric keys is refer to view variables. Commented Jun 30, 2014 at 13:25

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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'];
}

1 Comment

This is also very good. I think I'll do a combination of both answers.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.