Php 如何删除字符串中的最后一个逗号?
我一直在尝试使用substr和rtrim来解决这个问题,它一直在删除所有的逗号。如果没有,什么都不会出现。所以我基本上被困住了,需要一些帮助。。会被剥夺权利的Php 如何删除字符串中的最后一个逗号?,php,arrays,string,Php,Arrays,String,我一直在尝试使用substr和rtrim来解决这个问题,它一直在删除所有的逗号。如果没有,什么都不会出现。所以我基本上被困住了,需要一些帮助。。会被剥夺权利的 if(is_array($ids)) { foreach($ids as $id) { $values = explode(" ", $id); foreach($values as $value) { $value .= ',
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
if(is_数组($id)){
foreach($id作为$id){
$values=分解(“,$id”);
foreach($value作为$value){
$value.=',';
echo ltrim($value,“,”)。
;
}
}
}
通过rtrim更改ltrim:
ltrim-从字符串开头去除空白(或其他字符)
rtrim-从字符串末尾去除空白(或其他字符)
我猜您正在尝试获取一个由空格分隔的ID字符串组成的数组,并将其展平为逗号分隔的ID列表 如果这是正确的,您可以这样做:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
输出:
abc, def, ghi, jklm, nopq, rstu, vwxy
使用修剪()功能
如果你有这样一根绳子
使用此代码删除最后一个逗号
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
如果您的数组看起来像
[0] => 1,
[1] => 2,
[2] => 3,
...
以下内容应足够(不是最佳解决方案)
欢迎来到StackOverflow!一般来说,如果您提供示例输入、所需输出和当前获得的输出,以便清楚问题所在,则更容易帮助回答您的问题。使用$IDSRARY([0]=>1[1]=>2[2]=>3[3]=>4)值进行编辑不清楚你在问什么-请用更多的细节/代码改进你的问题我想一次从多个ID检索数据。所以它必须是1,2,3,4,而不是1,2,3,4,你确定你复制了所有的}?这段代码最后应该只使用一个额外的
。我同意这个答案,因为这正是OP想要做的。不客气,请回答您的第二个问题:将'where id=({$ids')更改为'where id in({$ids}')equal仅用于相等。使用'in'测试列表中是否存在。
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
[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..."