專案框架:CodeIgniter
在專案中,我們使用了 2 個表,例如“person”和“emailGroups”。我們通過組 ID 使用 json_encode 將人員保存在 "person" 表中。因為一個人可以屬于多個群體。
我們在 HTML 表格中列出人員。
<table>
<thead>
<tr>
<th>Name Surname</th>
<th>E-Mail</th>
<th>Process</th>
</tr>
</thead>
<tbody>
<tr>
<td>$personName</td>
<td>$personEmail</td>
<td><div class=\"custom-control custom-switch switch-lg custom-switch-danger mr-2 mb-1 mt-1\">
<input type=\"checkbox\" class=\"custom-control-input toggleState2\" name=\"mailStatus\" data-id='$groupId' data-target=\"$personId\" data-index=\"$baseUrl\" id=\"customSwitch2$personId\" $checked>
<label class=\"custom-control-label\" for=\"customSwitch2$personId\">
<span class=\"switch-text-left\">Remove</span>
<span class=\"switch-text-right\">Removed</span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
人表:
人表
我們有“person”表有一列作為“personEmailGroup”包含 JSON 包含如 ["1","2","4"]。我們想洗掉 personEmailGroup 列中包含 JSON 的 Id。例如我們只想洗掉“4”,之前包含Id的[“1”,“2”,“4”],洗掉后顯示為[“1”,“2”]然后更新。
洗掉功能碼:
$processToId = $this->input->post("personId"); // person Id who has multiple e-mail groups.
$processToGroupId = $this->input->post("groupId"); // the group Id contains JSON
$getEmailGroup = $this->db->where("(JSON_CONTAINS(person.personEmailGroup,'[\"$processToGroupId\"]')) > ",0)->where("personId", $processToId)->get('person')->row("personEmailGroup");
$getEmailGroup = json_decode($getEmailGroup);
foreach ($getEmailGroup as $gets) {
if (in_array($processToGroupId, $getEmailGroup)) {
unset($getEmailGroup[$gets]);
}
}
$data = array(
"personEmailGroup" => json_encode($getEmailGroup),
);
$process = $this->db->where("personId", $processToId)->update("person", $data);
if ($process) {
$dataJson['status'] = true;
echo json_encode($dataJson);
} else {
$dataJson['status'] = false;
echo json_encode($dataJson);
}
此代碼無效。也許它讓我們知道我們想要什么?我們需要通過作業代碼獲得有關此程序的新想法。提前致謝!
uj5u.com熱心網友回復:
因為您只有元素陣列,所以unset按值不起作用。您應該unset按元素索引 - 使用。所以需要找到元素索引,然后呼叫unset函式。這是您的代碼更新。
$processToId = $this->input->post("personId"); // person Id who has multiple e-mail groups.
$processToGroupId = $this->input->post("groupId"); // the group Id contains JSON
$getEmailGroup = $this->db->where("personId", $processToId)->get('person')->row("personEmailGroup");
$getEmailGroup = json_decode($getEmailGroup);
// remove group if exist
if (($key = array_search($processToGroupId, $getEmailGroup)) !== false) {
unset($getEmailGroup[$key]);
}
$data = array(
"personEmailGroup" => json_encode($getEmailGroup),
);
$process = $this->db->where("personId", $processToId)->update("person", $data);
if ($process) {
$dataJson['status'] = true;
echo json_encode($dataJson);
} else {
$dataJson['status'] = false;
echo json_encode($dataJson);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359568.html
