我在一个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"}
]
答案 0 :(得分:2)
这是一个建议。如果您想要一个数据结构,则仅回显一个。
// 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
]
);
答案 1 :(得分:0)
您可以使用函数array_merge,以便将数组合并为一个。 完成此操作后,您可以使用json_encode函数对该包含来自三个数组的所有数据的数组进行编码。