php数组拼接mysql in语句
数据分析
通常php后端接收前端1个数组参数时通常为:
-
数组:
['aa','bb','cc']
-
json数组字符串:
'["aa","bb","cc"]'
-
逗号隔开的字符串:
'aa,bb,cc'
先统一转为数组。
#json字符串转数组
$str = '["aa","bb","cc"]';
$arr = json_decode($str,true);
# ['aa','bb','cc']
#逗号隔开字符串转数组
$str = 'aa,bb,cc';
$arr = explode(',',$str);
# ['aa','bb','cc']
php数组拼接 in语句
mysql in 使用
-
数值:
select * from order where status in(1,2,3);
数值直接使用implode 将数组[1,2,3],转为字符串1,2,3,拼接即可
$arr = [1,2,3]; $str = implode($arr,','); # 1,2,3 $sql = "select * from order where status in({$str})"; # select * from order where status in(1,2,3)
-
字符串:
select * from order where status in('waitbuyerpay','waitsellersend','waitbuyerreceive');
字符串使用
implode($arr,',')
转成字符串为waitbuyerpay,waitsellersend,waitbuyerreceive
拼接的sql是有错误的可以
implode($arr,"','")
转成waitbuyerpay','waitsellersend','waitbuyerreceive
再在字符串两边拼上'
$arr = ['waitbuyerpay','waitsellersend','waitbuyerreceive']; $str = implode($arr,"','"); # waitbuyerpay','waitsellersend','waitbuyerreceive $sql = "select * from order where status in('{$str}')"; # select * from order where status in('waitbuyerpay','waitsellersend','waitbuyerreceive')