Accessing Multidimensional array with Codeigniter

2019-08-26 00:18发布

问题:

Ok, In my Codeigniter project I am passing a multidimensional array to my view. The issue I am having is access the data in the array. I use print_r and var_dump to see the array and it is being passed correctly to the view but I am having the hardest time access the data within it! I get this error message, "Trying to access parameter of non-object". Any suggestions?!

Here is the controller: profile.php

    <?php
        class Profile extends CI_Controller {

            public function __construct(){
                parent::__construct();
                $this->load->library('session');

                //Get user data
                $this->load->model('user_model');

            }

            public function user_lookup(){
                //get usering users data
                $email = $this->session->userdata('email');
                //get profile users data
                $username = $this->uri->segment(2,0);

                $user = array(
                            'users' => $this->user_model->getUserData($email),
                            'profile' => $this->user_model->getUserDataWithUsername($username)
                        );

                $this->load->view('profile_view', $user);
            }

        }
    ?>

And here is the view that is recieving the data: profile_view.php

<!DOCTYPE html>
<html>
    <body>
        <?php
             print_r($users[0]);
        ?>
     </body>
 </html>

The output of my print_r statement is:

Array ( [hometown] => Las Vegas [email] => johnmy@gmail.com [university] => UC Berkley [first_name] => Pete [last_name] => Smith [date] => 1992 ) 1

回答1:

Based on your code:

$this->load->view('profile_view', $user);

This mean that you supply array $user as view data. Therefore, on view $user is no longer exists.

You can only use it's element in view:

<?php
    echo $hometown;
    echo $email;
?>

If you want to use $user array in view, use this view load code in controller:

$this->load->view('profile_view', array('user' => $user ));

You can read more about Views in CodeIgniter.