PHP实现从逗号分隔用户ID字符串中移除指定用户ID数组
问题解决:移除Offer表中存储为字符串的指定用户ID
在Offer表中,某列以'1,2,3,4'格式的字符串存储授权用户ID,需通过多选下拉框选择要移除的用户ID并实现移除功能。最初的代码存在问题:即使只选择一个ID,也会删除所有授权用户ID。
问题根源与修正要点
- 多选下拉框的名称需要添加
[],提交后的值会自动转为数组格式 - 需将数据库中存储的用户ID字符串通过
explode()转换为数组,才能正确和要移除的ID数组做差集运算
初始错误代码
public function removeAccess(Offer $offer, Request $request) { $this->validate($request, [ 'private_access' => 'required', ]); $current_allowed = array($offer->private_allowed); $remove_allowed = $request->private_access; $allowed = array_diff_key($current_allowed, array_flip($remove_allowed)); $offer->private_access = $allowed; $offer->save(); return redirect()->back()->with('status', 'Publisher(s) successfully removed from private access.'); }
修正后的正确代码
public function removeAccess(Offer $offer, Request $request) { $this->validate($request, [ 'private_access' => 'required', ]); $current_allowed = explode(',', $offer->private_access); $remove_allowed = $request->private_access; $filtered = array_diff($current_allowed, $remove_allowed); $allowed = implode(',', $filtered); $offer->private_access = $allowed; $offer->save(); return redirect()->back()->with('status', '已成功移除指定发布者的私有访问权限。'); }
错误处理代码
return redirect()->back()->withErrors('发生了一个错误。');
内容的提问来源于stack exchange,提问作者Jarrod Estepp
相关产品推荐
相关产品推荐

