PHP从while循环字符串中删除最后2个字符

时间:2014-07-11 19:17:02

标签: php

我在循环语句中返回一个列表,并尝试从结果中删除最后两个字符:逗号和空格。

在尝试使用trim,rtrim,implode和strlength之前,这是我的类函数

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo $nameRow['username']."(".$pullrow['char_name']."), ";
        }
    }
}

如何删除最终分隔符?

3 个答案:

答案 0 :(得分:5)

与其混淆rtrimsubstr或类似内容,您可以更轻松地保留一系列结果,并implode。这样您就不必跟踪最后一条记录或要剥离的字符数:

function ReturnPlayerList()
{
    global $sql;
    $result = array();
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            $result[] = $nameRow['username']."(".$pullrow['char_name'].")";
        }
    }
    echo implode(", ", $result);
}

答案 1 :(得分:0)

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo rtrim($nameRow['username']."(".$pullrow['char_name']."), ",", ");
        }
    }
}

答案 2 :(得分:0)

我认为你也可以使用substr函数,如下所示: -

function ReturnPlayerList()
{
    global $sql;
    $pull = $sql->Query($GLOBALS['GET_PLAYERS']);
    while ($pullrow = mysqli_fetch_array($pull))
    {
        $name = $sql->Query($this->ReturnForumUser($pullrow['UID']));
        while ($nameRow = mysqli_fetch_array($name))
        {
            echo substr($nameRow['username']."(".$pullrow['char_name']."), ", 0, -2);
        }
    }
}