我在 PHP 文件中创建了三个数组,所有数组都从 MYSQL 数据库获取其元素。尽管我使用了 json_encode 方法来准备数组,但结果不是可解析的 JSON。
我对 JSON 和 PHP 非常陌生,但我尝试将三个数组编码为一个变量以及三个不同的变量。但在这两种情况下,当我回显结果时,它都不是有效的 JSON。
我在 PHP 文件的开头创建了数组。
$physicianArr = array();
$patientArr = array();
$apmtArr = array();
我使用这种通用方法来填充所有数组(行用于分解三个示例,不包含在代码中。)
if (mysqli_num_rows($resultPhysician) > 0) {
while($row=mysqli_fetch_assoc($resultPhysician)) {
$physicianArr[] = $row;
}
$physicianJSON = json_encode($physicianArr);
}
if (mysqli_num_rows($resultPatient) > 0) {
while($row=mysqli_fetch_assoc($resultPatient)) {
$patientArr[] = $row;
}
$patientJSON = json_encode($patientArr);
}
if (mysqli_num_rows($resultApmt) > 0) {
while($row=mysqli_fetch_assoc($resultApmt)) {
$apmtArr[] = $row;
}
$apmtJSON = json_encode($apmtArr);
}
结果:
当我在 Web 浏览器上输入 URL 来检索此 PHP 文件时,结果是三个单独的数组而不是一个 JSON:
[
{"UserID":"3","FirstName":"Jane","LastName":"Parkey"},
{"UserID":"4","FirstName":"Jamie","LastName":"Crane"},
{"UserID":"5","FirstName":"Jerry","LastName":"Martin"},
{"UserID":"6","FirstName":"Alexander","LastName":"Dollar"},
{"UserID":"8","FirstName":"Bob","LastName":"Loblaw"},
{"UserID":"11","FirstName":"Mary","LastName":"Robbins"},
{"UserID":"15","FirstName":"testy","LastName":"testy"}
][
{"UserID":"1","FirstName":"Joe","LastName":"Smith"},
{"UserID":"2","FirstName":"Adam","LastName":"Stone"},
{"UserID":"9","FirstName":"Michael","LastName":"Jordan"},
{"UserID":"10","FirstName":"Tom","LastName":"Holland"},
{"UserID":"12","FirstName":"test1","LastName":"test1"},
{"UserID":"19","FirstName":"Will","LastName":"Smith"},
{"UserID":"20","FirstName":"Joe","LastName":"Imburgia"}
][
{"apmtID":"1","PhysicianID":"15","apmtDate":"Jun 26, 2019","apmtTime":"09:00:00 AM","PatientID":"1"},
{"apmtID":"2","PhysicianID":"15","apmtDate":"test","apmtTime":"test","PatientID":"1"},
{"apmtID":"4","PhysicianID":"15","apmtDate":"Apr 20, 2019","apmtTime":"7:10:36 AM","PatientID":"1"}
]
最佳答案
这是一个建议。如果您想要一种数据结构,则只需回显一种。
// make sure all arrays exist
$physicianArr = [];
$patientArr = [];
$apmtArr = [];
if (mysqli_num_rows($resultPhysician) > 0) {
while($row=mysqli_fetch_assoc($resultPhysician)) {
$physicianArr[] = $row;
}
}
if (mysqli_num_rows($resultPatient) > 0) {
while($row=mysqli_fetch_assoc($resultPatient)) {
$patientArr[] = $row;
}
}
if (mysqli_num_rows($resultApmt) > 0) {
while($row=mysqli_fetch_assoc($resultApmt)) {
$apmtArr[] = $row;
}
}
echo json_encode(
[
'Physicians' => $physicianArr
'Patients' => $patientArr
'Ampt' => $apmtArr
]
);
关于php - 从多个 PHP 数组创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526518/