Php 代码';漂亮地';数组的输出(使用substr的foreach)
当我编写使用数组内容生成字符串的代码时,我希望写得“很好”Php 代码';漂亮地';数组的输出(使用substr的foreach),php,arrays,string,export,Php,Arrays,String,Export,当我编写使用数组内容生成字符串的代码时,我希望写得“很好” $array=['21260','777','32']; foreach($array as $value) $tmp=$tmp.$value."','"; $FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2)).")"; // the FINALE_STRING SHOULD BE THAT: $FINALE_STRING="('21260','777','32')" 用于
$array=['21260','777','32'];
foreach($array as $value)
$tmp=$tmp.$value."','";
$FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2)).")";
// the FINALE_STRING SHOULD BE THAT: $FINALE_STRING="('21260','777','32')"
用于改进我的Thx。使用内爆将数组值连接到字符串:
$array=['21260','777','32'];
$tmp=implode("','",$array);
$FINALE_STRING="('".$tmp."')";
演示:使用内爆将数组值连接到字符串:
$array=['21260','777','32'];
$tmp=implode("','",$array);
$FINALE_STRING="('".$tmp."')";
演示:您可以使用
您可以使用
您的代码除了一个小问题外还能正常工作;在您的substr
呼叫中有一个额外的)
$array=['21260','777','32'];
$tmp = ""; //removes the undefined variable error you will get
foreach($array as $value)
$tmp=$tmp.$value."','";
//old line:
// $FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2)).")";
$FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2).")";
输出:('21260'、'777'、'32')
除了一个小问题,您的代码还能正常工作;在您的substr
呼叫中有一个额外的)
$array=['21260','777','32'];
$tmp = ""; //removes the undefined variable error you will get
foreach($array as $value)
$tmp=$tmp.$value."','";
//old line:
// $FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2)).")";
$FINALE_STRING="('".substr($tmp,0,strlen($tmp)-2).")";
输出:('21260'、'777'、'32')
当我编写代码时,你忘记在for循环之外定义tmp
,加上你有一个额外的结束妄想,所以它失败了。实际上<代码>tmp
仍在范围内。他会遇到一个未定义的变量问题,但不会因此而失败。使用rtrim($tmp,“,”)@WillParky93正确!当我编写代码时,你忘记在for循环之外定义tmp
,加上你有一个额外的结束偏执,所以它失败了<代码>tmp
仍在范围内。他会遇到一个未定义的变量问题,但不会因此而失败。使用rtrim($tmp,“,”)@WillParky93正确!最佳答案-使用Op的代码。我仍然会评论tmp
这件事。好主意,我已经把它添加进去了。感谢@kabanusBest-answer-使用Op的代码。我仍然会评论tmp
这件事。好主意,我已经把它添加进去了。谢谢@kabanusThx,是带有substr的“long”命令,我没有发现正确的/nice。Thx,是带有substr的“long”命令,我没有发现正确的/nice。