如何对具有两个表
client
和 appointment
的数据库运行查询以输出如下 JSON:
{
"id": "1",
"app1": null,
"app2": null,
"app3":[
"cname": "John",
"clastname": "Doe",
"cemail": "[email protected]",
"cphone": "604",
],
"app4":[
"cname": "Mark",
"clastname": "Martini",
"cemail": "[email protected]",
"cphone": "778",
]
}
如您所见,当
null
x 字段为空时,我需要获取 app
并加载 client
表数据,其中 appx = cilentid
这是我的桌子
CREATE TABLE Client (
id INT(6),
cname VARCHAR(30) NOT NULL,
clastname VARCHAR(30) NOT NULL,
cemail VARCHAR(50),
cphone VARCHAR(50)
);
INSERT INTO Client
(`id`, `cname`, `clastname`, `cemail`, `cphone`)
VALUES
(25, 'John', 'Doe', '[email protected]', '604'),
(60 ,'Mark', 'Martini', '[email protected]', '778')
;
CREATE TABLE appointments (
id INT(6),
app1 INT(6) DEFAULT NULL,
app2 INT(6) DEFAULT NULL,
app3 INT(6) DEFAULT NULL,
app4 INT(6) DEFAULT NULL
);
INSERT INTO appointments
(`id`, `app1`, `app2`, `app3`, `app4`)
VALUES
(1,null,null,null,60),
(2,25,null,null,null)
;
您始终可以
SELECT
这些约会,循环遍历结果并将它们放入数组中,循环这些数组并从下一个表中获取您需要的任何内容。
$counter = 0;
$my_array=[];
$query = mysqli_query('SELECT * FROM appoints');
while ($result = mysqli_fetch_assoc($query)) {
foreach ($result as $key => $value) {
$my_array[$counter][$key] = ((int) $value > 0 ? (mysqli_fetch_assoc(mysqli_query('SELECT * FROM table WHERE id =' . (int) $usr))) : 'null');
}
$counter++;
}
var_export(json_encode($my_array));
最后你可以
json_encode
整个阵列。
我宁愿重新设计整个事情,但这会给你一个关于如何处理这个特定问题的好主意。