从逗号分隔的列表生成数组 - PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10835101/
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-24 23:10:16  来源:igfitidea点击:

Generate Array from a comma-separated list - PHP

phparraysstring

提问by michaelmcgurk

I have a variable defined like so: $var = "1, 2, 3";& I have an array: $thePostIdArray = array(1, 2, 3);

我有一个这样定义的变量:$var = "1, 2, 3"; & 我有一个数组:$thePostIdArray = array(1, 2, 3);

The Array above works great when looping through it but when I try to use the $varin place of the comma-separated list, problems occur.

上面的数组在循环时效果很好,但是当我尝试使用$var代替逗号分隔列表时,会出现问题。

So (perfect world) it could be $thePostIdArray = array($var);which would be the same as $thePostIdArray = array(1, 2, 3);.

所以(完美世界)它可能是$thePostIdArray = array($var); 这将与$thePostIdArray = array(1, 2, 3); 相同;.

Every attempt so far hasn't worked :'(

迄今为止的每一次尝试都没有奏效:'(

Is this even possible, or is there an easier workaround?

这甚至可能,还是有更简单的解决方法?

Thank you for any pointers.

感谢您的任何指点。

回答by janmoesen

Check out explode: $thePostIdArray = explode(', ', $var);

退房explode$thePostIdArray = explode(', ', $var);

回答by Subail Sunny

use explode function. this will solve your problem. structure of explode is like this

使用爆炸功能。这将解决您的问题。爆炸的结构是这样的

array explode ( string $delimiter , string $string [, int $limit ] )

now $delimiteris the boundary string, string $stringis the input string. for limit:

现在$delimiter是边界字符串,string $string是输入字符串。对于限制:

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

如果设置了 limit 并且为正数,则返回的数组将包含最大数量的 limit 元素,最后一个元素包含字符串的其余部分。

If the limit parameter is negative, all components except the last -limit are returned.

如果 limit 参数为负,则返回除最后一个 -limit 之外的所有组件。

If the limit parameter is zero, then this is treated as 1.

如果 limit 参数为零,则将其视为 1。

visit the following link. you can learn best from that link of php.net

访问以下链接。您可以从php.net 的链接中学到最好 的知识

回答by Waqar Alamgir

For developer who wants result with andin the end can use the following code:

对于and最终想要结果的开发人员可以使用以下代码:

$titleString = array('apple', 'banana', 'pear', 'grape');
$totalTitles = count($titleString);
if($totalTitles>1)
{
    $titleString = implode(', ' , array_slice($titleString,0,$totalTitles-1)) . ' and ' . end($titleString);
}
else
{
    $titleString = implode(', ' , $titleString);
}

echo $titleString; // apple, banana, pear and grape