我有这段代码我只是不知道如何输出视图中的每个项目,如firstname,lastname和username。
controller
{
$selected_users = array(
'username' => $username,
'firstname' => 'peter',
'lastname' => 'Sample'
);
$users = json_decode($this->session->userdata('users'), true);
$users[] = $selected_users;
$this->session->set_userdata('users', json_encode($users));
$this ->load->view('db_control\sess');
}
view:
$username = $this->session->userdata('users');
echo $username;
but it output all of it
output of this code is
[{ “用户名”: “newtest1”, “姓名”: “newtest1”, “姓”: “newtest1”},{ “用户名”: “sample_beth”, “姓名”: “sample_beth”, “姓” :“sample_beth”},{“username”:“default”,“firstname”:“default”,“lastname”:“default”}]
这是正确的,但我想输出用户名,姓氏和名字,但仍然是所有记录
答案 0 :(得分:0)
您可以简单地传递这样的数据 控制器
$data['selected_users'] = array(
'username' => 'testuser',
'firstname' => 'peter',
'lastname' => 'Sample'
);
$this->load->view('viewname',$data );
视图:
echo $selected_users['username'];
echo '<br>';
echo $selected_users['firstname'];
echo '<br>';
echo $selected_users['lastname'];
答案 1 :(得分:0)
在一个变量中设置selected_users数组。试试这个:
controller
{
$selected_users = array(
'username' => $userID,
'firstname' => 'peter',
'lastname' => 'Sample'
);
$this->session->set_userdata($selected_users);
}
view:
echo $this->session->userdata('username');
echo $this->session->userdata('firstname');
echo $this->session->userdata('lastname');
答案 2 :(得分:0)
在您的观点中,将code
更改为此<:p>
$username = json_decode($this->session->userdata('users'), TRUE);
foreach ($username AS $key => $value) {
echo 'Username: ' . $value['username'];
echo '<br/>';
echo 'First Name: ' . $value['firstname'];
echo '<br/>';
echo 'Last Name: ' . $value['lastname'];
echo '<br/><hr><br/>';
}
基本上,您正在将JSON
转换回Array,然后循环遍历它。