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‘)
    

php数组拼接mysql in语句

上一篇:《 Real-Time Compressive Tracking 》的个人理解


下一篇:怼不过产品经理?因为你不懂DDD领域建模与架构设计