尝试在PHP中使用json_encode

Here is my small script

$item="Inception";

$query="SELECT * FROM items WHERE item = '{$item}' LIMIT 1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) { 
    $item_id = $row['items_id'];
}   

$sql="SELECT AVG(rating) AS AverageRating FROM ratings WHERE item_id = '{$item_id}'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);

print(json_encode($row));

The output is this:

 {"0":"4.5","AverageRating":"4.5"}

My question is: Where is row "0" coming from? Is this normal?

mysql_fetch_array returns both a string association and a numeric association. Try mysql_fetch_assoc or mysql_fetch_row alone.

It is normal. mysql_fetch_array returns the row with both numeric and associative indexes. That's not an O, but a 0, meaning the first returned column.

See the doc of mysql_fetch_array: by default, it returns an array with both numeric and strings indexes. If you want only an associative array, use mysql_fetch_assoc or add MYSQL_ASSOC as second parameter of mysql_fetch_array.

That is happening because, as the documentation states, by default mysql_fetch_array returns both an associative array and a numeric one. If you just want the associative results, you can pass an extra parameter, like so:

$row = mysql_fetch_array($result, MYSQL_ASSOC);

Or if you just want the array indexed numerically:

$row = mysql_fetch_array($result, MYSQL_NUM);

Simply replace

$row = mysql_fetch_array($result);

with

$row = mysql_fetch_array($result, MYSQL_ASSOC);

and the zero will be gone.

The are 3 result types you can choose from. MYSQL_NUM which will return a numerical array, MYSQL_ASSOC which will return an associative array and is also what you appear to need, and MYSQL_BOTH which is the default and returns both.