数组转字符串(属性加单引号,逗号分隔)
数组转字符串
PHP
应用场景:SQL写操作应用插入表字段值;
数组 $data
$data = array(‘张三‘,‘男‘,‘20‘,‘‘安徽省合肥市 ‘);
转换如下:
#join
$str = " ‘ " . join("‘,‘", array_values($data) ) . " ‘ ";
#str_replace
$str = " ‘ ".str_replace( ",","‘,‘", implode(‘,‘,$data));
#array_map 函数式实现
$str = join( ‘, ‘,array_map(function( $v ){ return "‘".$v."‘";},$data) );
结果:‘张三‘,‘男‘,‘20‘,‘‘安徽省合肥市 ‘ ; 实现sql如下
$insertSql = " INSERT INTO user values({$str}) ";
时间: 2024-12-28 01:37:32