我一直在尝试使用substr、rtrim进行配置,它不断删除所有逗号。如果没有,什么也不会出现。所以我基本上陷入了困境,需要一些帮助。。会被事先告知的。
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
我猜您正试图获取一个由空格分隔的id组成的字符串数组,并将其展开为一个逗号分隔的id列表。
如果这是正确的,你可以这样做:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
输出:
abc, def, ghi, jklm, nopq, rstu, vwxy
通过rtrim:更改ltrim
ltrim—从字符串的开头去掉空白(或其他字符)
rtrim—从字符串的末尾去掉空白(或其他字符)
<?php
$ids = Array ( 1,2,3,4 );
$final = '';
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$final .= $value . ', ';
}
}
echo rtrim($final, ', ') . '<br>';
echo substr($final, 0, -2) . '<br>'; //other solution
}
?>
如果您的数组看起来像;
[0] => 1,
[1] => 2,
[2] => 3,
...
以下内容就足够了(不是最理想的解决方案);
$string = ''; // Create a variable to store our future string.
$iterator = 0; // We will need to keep track of the current array item we are on.
if ( is_array( $ids ) )
{
$array_length = count( $ids ); // Store the value of the arrays length
foreach ( $ids as $id ) // Loop through the array
{
$string .= $id; // Concat the current item with our string
if ( $iterator >= $array_length ) // If our iterator variable is equal to or larger than the max value of our array then break the loop.
break;
$string .= ", "; // Append the comma after our current item.
$iterator++; // Increment our iterator variable
}
}
echo $string; // Outputs "1, 2, 3..."
使用trim()函数。
如果你有一个像这样的字符串
$str="foo, bar, foobar,";
使用此代码可以删除最后一个逗号
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
输出:foo,bar,foobar