我正在处理这个程序,在这里我试图将字符串电子邮件分开,按照',然后我将其存储在数组中,然后附加' city'在foreach ..
$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
$result .= " city = '$v' ";
echo $result;
}
我的结果是
city = 'aa' city = 'aa' city = 'bb' city = 'aa' city = 'bb' city = 'cc' city = 'aa' city = 'bb' city = 'cc' city = 'dd'
但我希望它是,
city = 'aa' city = 'bb' city = 'cc' city = 'dd'
我的代码错了吗?..请指导我..
答案 0 :(得分:2)
将echo
移出循环,因为你在循环中构建整个字符串,这将每次都回显字符串。
$result="";
foreach($a as $v)
{
$result .= " city = '$v' ";
}
echo $result; // move it here
答案 1 :(得分:0)
您根据自己的代码获得了结果,echo
执行每个loop
的结果。
因此,要在$ result中获取最终值,echo
在loop
之外。
foreach($a as $v)
{
$result .= " city = '$v' ";
}
echo $result;
答案 2 :(得分:0)
删除结果中的字符串连接
$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
$result = " city = '$v' ";//changed $result .= " city = '$v' "; to $result = " city = '$v' ";
echo $result;
}
答案 3 :(得分:0)
你在foreach中回显$ result,所以你的字符串或变量是重复的。请尝试以下代码:
$email='aa,bb,cc,dd';
$a=explode(',',$email);
$result="";
foreach($a as $v)
{
$result .= " city = '$v' ";
}
echo $result;
答案 4 :(得分:0)
删除字符串concat ..
$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
$result = " city = '$v' "; // remove string concate..
echo $result;
}
另一种方法是在foreach循环之外的回声 ......
$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
$result .= " city = '$v' ";
}
echo $result; // echo outside the foreach loop
的输出强>
city = 'aa' city = 'bb' city = 'cc' city = 'dd'