在PHP中构建json对象数组时出错
在构建json对象数组时,我在php中遇到了一个大问题。我正在尝试从mysql中获取记录,然后将它们放在下面的格式中,但它不起作用 这就是我想要的:在PHP中构建json对象数组时出错,php,arrays,json,Php,Arrays,Json,在构建json对象数组时,我在php中遇到了一个大问题。我正在尝试从mysql中获取记录,然后将它们放在下面的格式中,但它不起作用 这就是我想要的: { "records":[ {"id": 1,"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"}, {"id": 2,"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"
{ "records":[ {"id": 1,"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"}, {"id": 2,"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"}, {"id": 3,"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"}, {"id": 4,"Name":"Around the Horn","City":"London","Country":"UK"}, {"Name":"B's Beverages","City":"London","Country":"UK"}, {"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"}, {"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"}, {"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"}, {"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"}, {"Name":"Bon app'","City":"Marseille","Country":"France"}, {"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"}, {"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"}, {"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"}, {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"}, {"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"} ] }
我得到了什么
["records",{"name":"abc","email":"test2@test.com"},{"name":"def","email":"test2@gmail.com"},{"name":"ghi","email":"test3@hotmail.com"}]
注意“records”后面的冒号(:)
我的PHP代码:
$rows[] = "records";
$a = mysql_query("", $connect);
while ($b = (mysql_fetch_array($a)) ){
extract($b);
$rows[] = array('name' => "$accountnumber", 'email' => "$email");
}
echo json_encode($rows);
您在错误的位置添加了
记录
级别,只是将其作为元素添加到数组中。这会将每一行添加为此元素的子元素($rows[“records”][
)
另外-如果可能,请避免使用
extract()
,而是从获取的数组中添加值。如果将记录添加到错误的位置,则只是将其作为元素添加到数组中。这会将每一行添加为此元素的子元素($rows[“records”][
)
另外-如果可能,避免使用extract()
,而是从获取的数组中添加值。为什么不使用json_encode()呢只要你能从数据库中以数组的形式检索数据,函数就可以了?@NigelRen请现在检查..我已经添加了我的代码在JSON中使用标志JSON\u FORCE\u OBJECT
,你的预期数据和你得到的数据是不同的一般说明-你应该开始远离旧的mysql\u
api-为什么不使用JSON\u encode()只要你能从数据库中以数组的形式检索数据,函数就可以了?@NigelRen请现在检查..我已经添加了我的代码在JSON中使用标志JSON\u FORCE\u OBJECT
,你的预期数据和你得到的数据是不同的一般说明-你应该开始远离旧的mysql\ucode>api-你是个天才!!谢谢Nigel Ren,你的回答帮助我构建了一个JSON响应,这正是我想要的。你真是个天才!!感谢Nigel Ren,您的回答帮助我构建了一个JSON响应,这正是我想要的。
$rows= [];
$a = mysql_query("", $connect);
while ($b = (mysql_fetch_array($a)) ){
$rows["records"][] = array('name' => $b["accountnumber"], 'email' => $b["email"]);
}
echo json_encode($rows);