我有這樣的代碼,返回了SQL查詢,JSON消除回聲-ED尾隨逗號PHP
<?php
$con=mysqli_connect("localhost","user","pw","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$con->set_charset("utf8");
$result = mysqli_query($con,"SELECT * FROM table");
echo "{";
while($row = mysqli_fetch_array($result))
{
echo '"' . $row['RowId'] . '"' . ":{";
echo '"Name": "' . $row['Name'] . '",';
echo '"Surname": "' . $row['Surname'] . '",';
echo '"MuEmail": "' . $row['MuEmail'] . '@mahidol.ac.th"';
echo '},';
}
echo "$bs";
echo "}";
mysqli_close($con);
?>
但回聲編輯文本的最後結果,像
{
...
"678":{
"Name": "xxx",
"Surname": "yyy",
"MuEmail": "[email protected]"}
,}
觀察尾隨逗號,這會導致JS的JSON.parse()失敗。
無論如何刪除這個逗號?
你爲什麼不使用替換while循環[破滅](http://php.net/manual/en/function.implode.php)呢? – Thamilan
使用json_encode($ row) – RJParikh
更好的做法是填充一個對象或數組,然後使用json_encode($ yourarrayorobject) –