我用 PHP 编写了一个脚本,它从 MySQL 数据库中获取值并将这些值输出为 JSON。但是,我遇到了问题。这是代码:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("stitchdex");
$query = mysql_query("SELECT image, price, description FROM {$_GET['table']}");
$jsonString = "{\"images\":[";
$numrows = mysql_num_rows($query);
$i=0;
while ( $row = mysql_fetch_array($query) ) {
$jsonString .= "{\"image\":\"{$row['image']}\", \"price\":\"{$row['price']}\", \"description\":\"{$row['description']}\"}";
if ( ($numrows-1) == $i ) echo "";
else echo ",";
$i++;
}
$jsonString .= "]}";
echo $jsonString;
?>
但它输出:
,,,,,,,,,,,,,,,,,{"images":[{"image":"priceguide1.jpg", "price":"", "description":"Diagram of Options"}{"image":"2ndamendfront.jpg", "price":"$109.00", "description":"Total of 3 laser etchings"}{"image":"DSC_0120.jpg", "price":"$99.00", "description":"Designer Kydex 1 Laser Etching"}{"image":"DSC_0121.jpg", "price":"", "description":"Lazer Etching on Back"}{"image":"gilbert.jpg", "price":"$109.00", "description":"Designer Kydex 2 Lazer Etchings"}{"image":"glock23-carbonfiber-red1.jpg", "price":"$79.00", "description":""}{"image":"irish1.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}{"image":"irish2.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}{"image":"klover-glock-2.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}{"image":"priceguide1.jpg", "price":"", "description":"Diagram of Options"}{"image":"2ndamendfront.jpg", "price":"$109.00", "description":"Total of 3 laser etchings"}{"image":"DSC_0120.jpg", "price":"$99.00", "description":"Designer Kydex 1 Laser Etching"}{"image":"DSC_0121.jpg", "price":"", "description":"Lazer Etching on Back"}{"image":"gilbert.jpg", "price":"$109.00", "description":"Designer Kydex 2 Lazer Etchings"}{"image":"glock23-carbonfiber-red1.jpg", "price":"$79.00", "description":""}{"image":"irish1.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}{"image":"irish2.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}{"image":"klover-glock-2.jpg", "price":"$129.00", "description":"Designer Kydex Two Tone Leather & 3 Laser Etchings Two on front One on Back"}]}
如果逗号分隔“图像”数组中的对象,这将是有效的 JSON,但出于某种原因,脚本首先输出所有逗号。这是为什么?
我是一名优秀的程序员,十分优秀!