我在代码点火器中遇到foreach
循环错误,它工作正常,但是一旦我将项目移动到新的主机,我就会收到循环错误。两台服务器都使用 PHP 7.2
这是第一个错误:
Message: array_slice() expects parameter 1 to be array, null given
这是第二个错误:
Message: Invalid argument supplied for foreach()
回溯说错误出在控制器中,我已经检查了很多次并尝试了很多方法,但仍然相同。
使用is_array
PHP函数无济于事,因为它只会隐藏错误消息,但函数不会像以前一样工作。
控制器:
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header', $data);
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// Get username
$username = $this->input->post('email');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'id' => $user_id,
'email' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
// Set message
$this->session->set_flashdata('user_loggedin', 'Login Success');
redirect('users/account');
} else {
// Set message
$this->session->set_flashdata('login_failed', 'Login Faild');
redirect('users/login');
}
}
}
public function account($id = NULL){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['users'] = $this->user_model->get_users($this->session->userdata('id'));
$data['title'] = 'Account';
$this->load->view('templates/user_header', $data);
$this->load->view('users/account', $data);
$this->load->view('templates/user_footer');
}
循环代码:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
型:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
重写以下代码:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
如:
<div><p><?php echo $users['first_name'] ?></p></div>
因为:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
此代码不会返回多维数组...您已经使用了row_array()
它将是一个数组。