从连接的查询字符串结果中删除尾随逗号

从连接的查询字符串结果中删除尾随逗号

问题描述:

hope you can help, tearing my hair out here!

I have...

$result = mysqli_query($con,'SELECT this FROM that');

while($row = mysqli_fetch_array($result)) 
    {
        echo $row['this'] . ',';
    }

Which returns... 222,225,243,256,260,269,273,280,295,296,

I need to remove the last comma to give me just... 222,225,243,256,260,269,273,280,295,296

I've tried trim rtrim substr and everything else I could find but none of them work. Think it's to do with the concatenation of the $row['this'] . ',' but I cant figure out how to resolve it!

Any help would be appreciated.

Cheers, Mark.

希望你能帮忙,把我的头发撕成碎片! p>

我有 ... p>

  $ result = mysqli_query($ con,'SELECT this FROM that'); 
 
而($ row = mysqli_fetch_array($ result))
 {  
 echo $ row ['this']。  ','; 
} 
  code>  pre> 
 
 

返回... 222,225,243,256,260,269,273,280,295,296, p>

我需要删除 最后一个逗号给我... 222,225,243,256,260,269,273,280,295,296 p>

我试过 trim code> rtrim code> substr 代码>以及我能找到的所有其他内容,但它们都不起作用。 认为这与 $ row ['this']的串联有关。 ',' code>但我无法弄清楚如何解决它! p>

任何帮助都将不胜感激。 p>

干杯, 标记。 p> div>

you can use implode

while($row = mysqli_fetch_array($result)) 
    {
        $a[]= $row['this'];
    }

$b = implode(',',$a);

print_r($b);

function for implode

function imp($c){
        $d= implode(',',$c);
        return $d;
    }


$b = imp($a);

print_r($b);

Just let MySQL do the work for you:

$result = mysqli_query($con, 'SELECT GROUP_CONCAT(this, ',') as thises FROM that');

This constructs the results as a comma-delimited string. You can refer to it by its name, thises.

Use rtrim to remove last comma.

rtrim($my_string,',');

You can use substr()

This is your code

$result = mysqli_query($con,'SELECT this FROM that');

while($row = mysqli_fetch_array($result)) 
{
   echo $row['this'] . ',';
}

Code Should like this

$result = mysqli_query($con,'SELECT this FROM  that');
$my_string = "";
while($row = mysqli_fetch_array($result)) 
{
   $my_string .= $row['this'] . ',';
}
$my_final_string = substr($my_string, 0, strlen($my_string)-1);
echo $my_final_string;

Explanation

 substr(string,start,length) 

string = Your generated string

start = From which position you want to start the string.

length = A positive number - The length to be returned from the start parameter. Negative number - The length to be returned from the end of the string