用于逗号分隔值的 PHP 'foreach'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17526300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:02:34  来源:igfitidea点击:

PHP 'foreach' for comma separated values

phpforeachcomma

提问by Bas

I have a Variable like this:
$variable = 'value1, value2, value3, value4, value5';
How to get a foreach loop for every comma separated value?

我有一个这样的变量:
$variable = 'value1, value2, value3, value4, value5';
如何为每个逗号分隔值获取 foreach 循环?

回答by Simon King

Try exploding the string into an array first like this $array = explode(', ',$variable);and then you can use a foreach on the resulting array.

尝试首先像这样将字符串分解为数组$array = explode(', ',$variable);,然后您可以在结果数组上使用 foreach。

回答by Rajeev Ranjan

   $variable = 'value1, value2, value3, value4, value5';
   $var=explode(',',$variable);
   foreach($var as row)
    {
    //do your code here
    }

回答by Hearaman

Use explodemethod to split the string to array and iterate the array. Visit the explode()function manual http://php.net/manual/en/function.explode.php

使用explode方法将字符串拆分为数组并迭代数组。访问explode()函数手册http://php.net/manual/en/function.explode.php

Code:

代码:

                $variableAry=explode(",",$variable); //you have array now
                foreach($variableAry as $var)
                {
                    echo $var. "<br/>";
                }

回答by Manish Shukla

You can do this.

你可以这样做。

    $variable = 'value1, value2, value3, value4, value5';
    $arrs = explode(',', $variable);
    foreach($arrs as $arr){
        //do somthing..
    }

I hpe you got your answare

我希望你得到了答案