我需要从最后一个回显文件中删除逗号。所以我需要从行"$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 = '';
echo '{name:"'.$aSong['Artist'].' '.$aSong['Title'].
'",mp3:"http://domain.com/uploads/audio/'.$aSong['ID'].'.mp3"},';
}
答案 0 :(得分:4)
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,',');
您也可以只填充一个数组:
$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);
您还需要引用您的JSON密钥,以便{mp3:"http...mp3"}
变为{"mp3":"http...mp3"}
。如果您正在尝试将JSON输出到浏览器以获取AJAX或其他任何内容,那么您需要这样的内容:
echo '{"0":[' . implode(',',$tmp_arr) . ']}';
获得所有输出后,请将其移至JSONlint.com并验证。
答案 1 :(得分:1)
一个简单的解决方案是使用辅助变量来跟踪您是否在第一个元素。如果您在第一个元素不,请在开头括号前输出逗号。