我想从foreach php循环中创建一维JSON输出。但是我当前的代码是打印以逗号分隔的单独JSON。
我正在使用PHP 5.5.38版本
<?php
$phone_num = $_GET["phonenum"];
// Initialize variable for database credentials
$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'yyyy';
$dbname = 'zzzz';
$connect = mysql_connect("localhost","xxxx","yyyy") or die('Database Not Connected. Please Fix the Issue! ' . mysql_error());
mysql_select_db("zzzz", $connect);
$querycallid = "SELECT CallSid FROM show_details WHERE phone_number = $phone_num ORDER BY CallSid DESC LIMIT 10";
$callid = mysql_query($querycallid, $connect);
$carray=array();
while($callidres = mysql_fetch_object($callid))
{
$carray[] = $callidres->CallSid;
}
$carray=array_filter($carray);
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($dblink->connect_errno)
{
printf("Failed to connect to database");
exit();
}
//Initialize array variable
$pdbdata = array();
$presult = $dblink->query("SELECT patient_name, age, disease, contact_no, sex FROM show_header WHERE phone_number = $phone_num");
//Fetch into associative array
while($prow=$presult->fetch_assoc())
{
$pdbdata[]=$prow;
}
$dbdata = array();
foreach($carray as $id)
{
//Fetch comments from show_details table
$result = $dblink->query("SELECT datetime, comment FROM show_details WHERE CallSid = $id");
//Fetch into associative array
$dbdata[] = $result->fetch_assoc();
}
$farray = array_merge($pdbdata, $dbdata);
//Print array in JSON format
$farray = str_replace(array('[', ']'), '', htmlspecialchars(json_encode($farray), ENT_NOQUOTES));;
echo $farray;
?>
我的预期结果应该是这样。
{
"patient_name":"Mike",
"age":"26",
"disease":"arthritis",
"contact_no":"9876543210",
"sex":"Male",
"datetime":"07-16-2019 11:57:39",
"comment":"day 2 comment 1",
"datetime":"06-15-2019 15:09:01",
"comment":"patient wants appointment for tomorrow",
"datetime":"05-10-2019 12:07:34",
"comment":"comment 1",
}
但是我的当前结果显示如下。
{
"patient_name":"Mike",
"age":"26",
"disease":"arthritis",
"contact_no":"9876543210",
"sex":"Male"
},
{
"datetime":"07-16-2019 11:57:39",
"comment":"day 2 comment 1"
},
{
"datetime":"06-15-2019 15:09:01",
"comment":"patient wants appointment for tomorrow"
},
{
"datetime":"05-10-2019 12:07:34",
"comment":"comment 1"
}
我尝试将数组与$pdbdata
和$dbdata
之类的代码中的各种结果分开,然后合并到一个JSON中。但是它仍然显示输出,并用逗号分隔。请帮助我解决代码中的错误。