繁体   English   中英

如何在CodeIgniter控制器中向数组添加键?

[英]How to add keys to array in CodeIgniter controller?

我正在为用户(用户主页,而不是其他人看到访问权限)创建简单的个人资料页面。 我的控制器:

<?php
class Profile extends CI_Controller {

    public function __construct()
        {
                parent::__construct();
                $this->load->model('Profile_model');
                $this->load->database();
                if (!$this->tank_auth->is_logged_in()) 
                    redirect('auth/login');
        }

        public function index()
        {
                $user_id = $this->tank_auth->get_user_id();

                $data = $this->Profile_model->getUserAccountInfoById($user_id);
                $data[] = $this->Profile_model->getUserProfileInfoById($user_id);

                $this->load->view('profile/profile', $data);
        }
}

我的模特:

<?php
class Profile_model extends CI_Model {

        public function __construct()
        {
                $this->load->database();

        }

        public function getUserAccountInfoById($user_id)
        {
                $query = $this->db->get_where('user_accounts', array('id' => $user_id));
                return $query->row_array();
        }
        public function getUserProfileInfoById($user_id)
        {
                $query = $this->db->get_where('user_profiles', array('user_id' => $user_id));
                return $query->row_array();
        }
}

并查看文件:

<h2><?php echo $username; ?></h2>
<h2><?php echo $longitude; ?></h2>
<h2><?php echo $latitude; ?></h2>

问题来自于我在user_accounts表中有用户名但在user_profiles表中有经度/纬度。 如果我单独使用模型方法,那么一切都很好,所以在模型内部一切正常。 但是当我尝试从两个表传递给我的视图数据时,我得到错误:

Undefined variable: longitude

我的问题是关于向$ data数组添加键/值。 我试图谷歌和我发现我必须添加[]但它仍然无法工作(相同的错误)。

使用array_merge来激活2个数组。你正在创建一个嵌套数组。 var_dump($data)将显示数组的内容。

$data是一个数组。当你创建$data[]=... ,你正在将另一个数组推送到data数组。所以第二个数组现在是一个嵌套数组。 longitude现在不在数组的第一级。 它在第二级(嵌套)。

$data1 = $this->Profile_model->getUserAccountInfoById($user_id);
$data2 = $this->Profile_model->getUserProfileInfoById($user_id);
$data = array_merge($data1 , $data2 );
$this->load->view('profile/profile', $data);

或者你可以根据需要访问嵌套数组。首先打印内容然后很容易决定如何访问嵌套数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM