简体   繁体   中英

error while building json object array in PHP

I'm facing a big problem in php while building a json object array. I'm trying to fetch records from mysql and then put them in the below format but it doesn't work.

This is how i want :

{ "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"} ] }

what i get

["records",{"name":"abc","email":"test2@test.com"},{"name":"def","email":"test2@gmail.com"},{"name":"ghi","email":"test3@hotmail.com"}]

notice the colon (:) after the "records".

My PHP CODE :

$rows[] = "records";


$a = mysql_query("", $connect);
while ($b = (mysql_fetch_array($a)) ){
extract($b);
$rows[] = array('name' => "$accountnumber", 'email' => "$email"); 
}

echo json_encode($rows);

You are adding the records level in the wrong place, you are just adding it as an element to the array. This adds each row as a child of this element ( $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);

Also - avoid using extract() if possible and add the values from the array you fetch instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM