开发者

How can I strip the comma from the last echo in a while loop?

I need to strip the comma from the last echoed file. So I need to remover the come from the line "$aSong['ID'].'.mp3"},". On the last one that is echoed

while ( $aSong = mysql_fetch_array($sql_get_files) ) {
        //Creates an array of $thisSong[ID], $thisSong[Title], etc.
        // substr removes the first 4 letters of the KEY
        foreach ( $aSong as $sKey => $sValue )
            $thisSong[substr($sKey,4)] = stripslashes($sValue);
        //Ditch $thisSong for the prev value
        $aSon开发者_运维知识库g = $thisSong; unset($thisSong);
        $mp3r = '';
        echo '{name:"'.$aSong['Artist'].' '.$aSong['Title'].
             '",mp3:"http://domain.com/uploads/audio/'.$aSong['ID'].'.mp3"},';
}


while ( $aSong = mysql_fetch_array($sql_get_files) ) {
        //Creates an array of $thisSong[ID], $thisSong[Title], etc. substr removes the first 4 letters of the KEY
        foreach ( $aSong as $sKey => $sValue ) $thisSong[substr($sKey,4)] = stripslashes($sValue);
        //Ditch $thisSong for the prev value
        $aSong = $thisSong; unset($thisSong);
        $mp3r = '';
        $tmp.= '{"name":"'.$aSong['Artist'].' '.$aSong['Title'].'","mp3":"http://domain.com/uploads/audio/'.$aSong['ID'].'.mp3"},';
}
echo rtrim($tmp,',');

You could also just populate an array:

$tmp_arr = array();
while ( $aSong = mysql_fetch_array($sql_get_files) ) {
        //Creates an array of $thisSong[ID], $thisSong[Title], etc. substr removes the first 4 letters of the KEY
        foreach ( $aSong as $sKey => $sValue ) $thisSong[substr($sKey,4)] = stripslashes($sValue);
        //Ditch $thisSong for the prev value
        $aSong = $thisSong; unset($thisSong);
        $mp3r = '';
        $tmp_arr[] = '{"name":"'.$aSong['Artist'].' '.$aSong['Title'].'","mp3":"http://domain.com/uploads/audio/'.$aSong['ID'].'.mp3"}';
}
echo implode(',',$tmp_arr);

You also need to quote your JSON keys so {mp3:"http...mp3"} becomes {"mp3":"http...mp3"}. If you're trying to output JSON to the browser for AJAX or whatever, you'll need something like this instead:

echo '{"0":[' . implode(',',$tmp_arr) . ']}';

Once you have all your output, take it over to JSONlint.com and validate it.


A simple solution is to use an auxiliary variable to keep track of whether you're at the first element or not. If you're not at the first element, output a comma before the opening brace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜