好吧,我所拥有的是一个非常简单的XAMPP设置,其中包含一个包含两行的单个表的数据库。我有一个PHP脚本随机抓取其中一行,然后在JSON中打印生成的查询。无论出于何种原因,虽然JSON有'列' (并不是真的想把它们称为列,因为JSON不能列,但是,是的......)实际上并不存在于表中。
我对XAMPP堆栈中的所有内容都很陌生,所以如果这是一个愚蠢的问题,我会提前道歉。
这是我的表:
以下是生成的JSON:
{"0":"1","id":"0.9645465863538408","1":"Big Mac","name":"Big Mac","2":"A double layer of sear-sizzled 100% pure beef mingled with special sauce on a sesame seed bun and topped with melty American cheese, crisp lettuce, minced onions and tangy pickles.","description":"A double layer of sear-sizzled 100% pure beef mingled with special sauce on a sesame seed bun and topped with melty American cheese, crisp lettuce, minced onions and tangy pickles.","3":"http:\/\/www.mcdonalds.com\/content\/dam\/McDonalds\/item\/mcdonalds-Big-Mac.png","imgSrc":"http:\/\/www.mcdonalds.com\/content\/dam\/McDonalds\/item\/mcdonalds-Big-Mac.png","4":"2","upVotes":"2","5":"1","downVotes":"1","6":"0.9645465863538408"}
(" 0"," 1"等等不存在于表格中)
这是我的php:
$password = "";
$usertable = "mcdonalds";
//Connect
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to $hostname . Please try again later.");
mysql_select_db($dbname);
//Fetch
$query = "SELECT * FROM `McDonalds`AS r1 JOIN(SELECT (RAND() *(SELECT MAX(id) FROM `McDonalds`)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
//Print
echo json_encode($row);
答案 0 :(得分:2)
使用mysql_fetch_assoc
代替mysql_fetch_array
。默认情况下,mysql_fetch_array
返回一个数组,其中包含每列的命名和数字索引。
或者您可以使用mysql_fetch_array($result, MYSQL_ASSOC)
。默认的第二个参数是MYSQL_BOTH
,这会导致您看到的结果。