简体   繁体   中英

Convert PHP array from mysql to JSON format

I'm trying to convert the result array from Mysql to JSON format, the format doesn't seems to be correct, a comma is missing between each object. Please advice, thank you.

I'm aware that im using the deprecated version of php here.

$result = mysql_query("SELECT * FROM patientvaccinedetail")or 
die(mysql_error());

while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {


 $specific = ["message" => $row["message"],
              "mobile" => $row["mobile"]];

             print_r (json_encode($specific)); 
}

Current Result:

{"message":"hello","mobile":"12345678"}{"message":"hi","mobile":"87878965"}

Desired Result:

{"message":"hello","mobile":"12345678"}, {"message":"hi","mobile":"87878965"}

You have to use array and at end of loop you have to echo result

$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
     $specific[] = ["message" => $row["message"],
                  "mobile" => $row["mobile"]];
}
echo json_encode($specific); 

Please moved json_encode() to outside of while loop.

$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
 $specific = ["message" => $row["message"],
              "mobile" => $row["mobile"]];          
}
print_r(json_encode($specific)); 

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