我正在尝试允许用户创建一个候选名单,但是我在短名单中添加了一个东西,它会覆盖那里的其他内容,我做错了什么?
function validate_add_cart_item($id){
$this->db->select('candidates.candidate_id, candidates.first_name, candidates.surname, candidates.DOB, candidates.talent, candidates.location, candidates.availability_order, candidates.availability, candidates.availability_comments, candidate_assets.url, candidate_assets.asset_size')
->from('candidates')
->join('candidate_assets', 'candidate_assets.candidates_candidate_id = candidates.candidate_id', 'left')
->where('candidate_assets.asset_size', 'small')
->where('candidate_assets.asset_type', 'image')
->where('candidates.candidate_id', (int)$id)
->limit(1)
->order_by('candidates.availability_order', 'DESC');
$query = $this->db->get();
//die($this->db->last_query());
// Check if a row has been found
if($query->num_rows > 0 ){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'name' => $row->first_name." ".$row->surname,
'location' => $row->location,
'talent' => $row->talent,
'image' => $row->url
);
$this->session->set_userdata('shortlist', array($data));
return TRUE;
}
// Nothing found! Return FALSE!
} else {
return FALSE;
}
答案 0 :(得分:1)
$this->session->set_userdata('shortlist', array($data));
不会将$ data附加到shortlist
,而是使用包含一个元素的数组覆盖它:$ data中的当前数据。
你可能(未经测试)想要:
if($query->num_rows > 0 ) {
$data = array();
foreach ($query->result() as $row)
{
// append the new "record" to the array $data
$data[] = array(
'id' => $id,
'name' => $row->first_name." ".$row->surname,
'location' => $row->location,
'talent' => $row->talent,
'image' => $row->url
);
}
$this->session->set_userdata('shortlist', $data);
return TRUE;
}
else {
...
答案 1 :(得分:1)
foreach(...){
// ...
$this->session->set_userdata('shortlist', array($data));
}
您多次覆盖以前的用户数据。不应该这样,你应该创建一个数组,并调用set_userdata一次。
$udata = array();
foreach(...){
// ...
$udata []= $data;
}
$this->session->set_userdata('shortlist', $udata);
编辑:
你的查询只返回一行,你可能想要更新你的数组,而不是覆盖它,所以像这样:
$udata = $this->session->get_userdata('shortlist');
foreach(...){
// ...
$udata []= $data;
}
$this->session->set_userdata('shortlist', $udata);