簡體   English   中英

PHP中構建json對象數組時出錯

[英]error while building json object array in PHP

在構建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);

您將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() ,而是從您獲取的數組中添加值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM