用逗号插入数组字符串,然后将其分开

时间:2018-04-26 22:14:57

标签: php arrays comma implode

几个字段值是一个类似于此的字符串: "IDX, CLV1, FLST, MRIS, RCOM, VOW, CLV2, HTA, CYBR, ILAX, HOL"

当我通过$dataValues = implode(", ", $ArrayValues);运行它时,它被逗号分开,我需要将该字符串保留为一个值。

这里有更多代码:

foreach($result as $listing){  //loops throught every listing.
$fields = $listing->toArray(); //convert listing fields and values to array

 foreach($fields as $field => $value){
    $ArrayValues[] = $value; //value being added to array
    $ArrayFields[] = $field; //field name being added to array
    unset($value); 
    unset($field);
 }
 //CREATE THE MYSQL STRING FOR THE VALUES.
 $dataValues = implode(", ", $ArrayValues); 
 unset($ArrayValues);

 //CREATE THE MYSQL STRING FOR THE FIELD NAMES
 $fieldTitleNames = '`' . implode('`, `', $ArrayFields) . '`'; 
 unset($ArrayFields);

 //CONVERTE FIELDS ARRAY TO MYSQL STRING   
 $fieldTitleNames = '`' . implode('`, `', $ArrayFields) . '`';
 unset($ArrayFields);

 //CONVERT VALUES ARRAY TO MYSQL STRING       
 $fieldTitleNames = '`' . implode('`, `', $ArrayFields) . '`';
 unset($ArrayFields);

 $sql1 = "INSERT INTO ".$table_name." ($fieldTitleNames) VALUES $dataValues)";
}

感谢您的耐心等待。

1 个答案:

答案 0 :(得分:0)

instead of implode after crating the array, create a string as you loop

so

$ArrayValues[] = $value; //value being added to array

becomes

$dataValues.=  $value.',';

inside the loop.

you should initialise the string $dataValues before the loop:

$dataValues='';

and after the loop remove the last added comma

$dataValues=rtrim(',',$dataValues);

this avoids the side effect of using implode in your case