PHP查询MySQL时如何将SET数据类型列的取值返回为数组
MySQL SET类型字段查询结果转数组实现方案
MySQL的SET类型字段默认返回逗号分隔的字符串,你可以通过以下两种方式实现转数组:
方法1:PHP侧直接拆分(兼容性最好)
SET类型的返回值天然是逗号分隔的无空格字符串,直接用explode()拆分即可,修改后的代码如下:
$getfirstlevel=mysqli_query($db,"SELECT * FROM aaa_menu WHERE type='page' and id = '$item' and level = 'first' and status = 'Active' ORDER BY menu_order ASC"); while($flrow=mysqli_fetch_assoc($getfirstlevel)){ $account_select_status_fl=$flrow['account_select_status']; $account_type_status_fl = $flrow['account_type']; // SET字段转数组 $account_type_arr = empty($account_type_status_fl) ? [] : explode(',', $account_type_status_fl); // 后续直接使用$account_type_arr即可 }
注:增加empty判断是为了避免SET字段为空时,explode返回包含空字符串的无效数组元素。
方法2:SQL侧直接转JSON数组(适用于MySQL 5.7+版本)
可以直接在查询时用MySQL的JSON函数处理,返回JSON格式的数组,PHP侧直接解析即可:
// 修改查询语句,单独处理SET字段 $sql = "SELECT *, JSON_ARRAY(account_type) as account_type_arr FROM aaa_menu WHERE type='page' and id = '$item' and level = 'first' and status = 'Active' ORDER BY menu_order ASC"; $getfirstlevel=mysqli_query($db,$sql); while($flrow=mysqli_fetch_assoc($getfirstlevel)){ $account_select_status_fl=$flrow['account_select_status']; // 直接解析JSON得到数组 $account_type_arr = json_decode($flrow['account_type_arr'], true); }
内容的提问来源于stack exchange,提问作者philliptoronto
相关产品推荐
相关产品推荐

