在构建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":"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"}]
在“记录”之后注意冒号(:)。
我的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);
答案 0 :(得分:3)
您将records
级别添加到错误的位置,只是将其作为元素添加到数组中。这会将每一行添加为该元素($rows["records"][]
)的子元素...
$rows= [];
$a = mysql_query("", $connect);
while ($b = (mysql_fetch_array($a)) ){
$rows["records"][] = array('name' => $b["accountnumber"], 'email' => $b["email"]);
}
echo json_encode($rows);
此外-尽可能避免使用extract()
,而是从您获取的数组中添加值。