删除回显的PHP中的尾随逗号

时间:2016-04-27 06:31:20

标签: php json

我有这个代码,它以JSON

的形式返回SQL查询
<?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": "zzz@example.com"}
,} 

观察尾随的逗号,这使得JS的JSON.parse()失败。

无论如何要删除这个逗号?

3 个答案:

答案 0 :(得分:0)

使用正确的json创建

$("tr[id="+row.id+"]")

试试这个,它会影响你的json并解决你的问题。

答案 1 :(得分:0)

您可以使用条件查看它是否是最后一行,如果是,则不输出逗号。

请参阅更新的代码:

<?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");

$row_count = 0;
$i = 0;
$row_count = mysqli_num_rows($result);

echo "{";

while($row = mysqli_fetch_array($result))
{
  $i++;
  echo '"' . $row['RowId'] . '"' . ":{";
  echo '"Name": "' . $row['Name'] . '",';
  echo '"Surname": "' . $row['Surname'] . '",';
  echo '"MuEmail": "' . $row['MuEmail'] . '@mahidol.ac.th"';
  if($i < $row_count){
      echo '},';
  }else{
      echo '}';
  }
}
echo "$bs";
echo "}";

mysqli_close($con);
?>

答案 2 :(得分:0)

  • 最好的方法是创建一个像

    这样的对象数组
    $json = array();  
    while($row = mysqli_fetch_array($result))  
    {  
       // create an object  
       $obj = new stdClass();  
       // add values to the object  
       $obj->Name = $row['Name'];  
       $obj->Surname= $row['Surname'];  
       $obj->MuEmail= $row['MuEmail'] . "'@mahidol.ac.th'";      
       // append the object to the array  
       $json["Reords"][] = $obj;  
    }  
    echo json_encode($json);   
    
  • 按照您的方式,只需使用以下代码替换您的while循环

    $currentRow = 1;   
    $count = mysqli-num_rows($result);  
    while($row = mysqli_fetch_array($result))  
    {  
       echo '"' . $row['RowId'] . '"' . ":{";  
       echo '"Name": "' . $row['Name'] . '",';  
       echo '"Surname": "' . $row['Surname'] . '",';  
       echo '"MuEmail": "' . $row['MuEmail'] . '@mahidol.ac.th"';  
       if($currentRow == $count)  
       {  
           echo '}';  
       }  
       else  
       {  
           echo '},';  
       }  
       $currentRow++;  
    }