[英]SEARCHING with some condition in codeigniter
我有一個使用codeigniter的web項目。 我在項目中搜索時遇到問題。 我必須顯示搜索頁面的多個結果與一些關鍵字。 這是我的模特
function find_user($like){
$this->db->from('user');
$this->db->like('name', $like,'after');
$result =$this->db->get();
return $result->result_array();
}
在我的用戶表中,包含
id | name | place_code
在用戶表中,列place_code
用於顯示來自用戶的位置
這是我的控制器
function search(){
$query = $this->input->post('query_cari');
$find = $this->m_user->find_user($query);
foreach ($find as $key) {
$code = $key['place_code'];
if ($code == '1') {
$place = 'Secretray';
}elseif($code == '2'){
$place = 'OB';
}elseif($code == '3'){
$place ='Manager';
}
}
$data['result'] = $find;
$data['place'] = $place;
$this->load->view('home/search',$data);
}
這是我的控制器代碼,包括從辦公室用戶獲取位置的logic
。 但問題是,當我得到一個結果只有1
結果時,這個place
是正確的。 但如果我獲得超過1分的結果, place
是哪里錯了,只是顯示了place
對所有的結果是place
從最后結果的搜索。 我想要的是,所有的結果都顯示了自己的place
。
在這里,我的觀點
<?php foreach ($find as $key: ?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $key['id'] ?></td>
<td><?php echo $key['name'] ?></td>
<td><?php echo $place ?></td>
</tr>
</tbody>
</table>
<?php endforeach ?>
你總是得到最后的位置是正常的,因為你的邏輯是不正確的。 首先,您的模型中存在錯誤。 其次,您可以改進模型代碼:
function find_user($like)
{
$this->db->like('name', $like, 'after');
return $this->db->get('user')->result();
}
現在,在您的控制器中,您希望根據place_code
的值更改變量place
。 您可以實時向stdClass()
添加新密鑰(或更改現有密鑰stdClass()
,如下所示:
foreach($find as $i => $result)
{
// By default, we assume the 'place_code' is equal to '1'
$find[$i]->place = 'Secretray';
if($result->place_code == '2')
$find[$i]->place = 'OB';
else
$find[$i]->place = 'Manager';
}
$data['find'] = $find;
$this->load->view('home/search', $data);
最后,在您看來:
<?php foreach ($find as $result){ ?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $result->id; ?></td>
<td><?php echo $result->name; ?></td>
<td><?php echo $result->place; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.