gpt4 book ai didi

PHP json_encode

转载 作者:行者123 更新时间:2023-11-29 23:24:31 27 4
gpt4 key购买 nike

这是我目前的脚本:

 //... PDO CONNECTION AND QUERY //...*

$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);

foreach ($result as $row){
$return[]=array('employeeid'=>$row['employeeid'],
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
}
$dbh = null;

header('Content-type: application/json'); echo '' .
json_encode($return) .'';

这给出了如下结果:

[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '001',
...,
...
}
]

[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '002',
...,
...
}
]

但我想要的是这样的结果(因此每个员工都有一个带有多个请求的对象):

[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'requests': [
{
'id': '001',
...,
...
},
{
'id': '002',
...,
...
}
]
}
]

有人可以帮我解决这个问题吗?

提前致谢,

一月

最佳答案

您需要在每个员工数组中包含 requests 记录:

foreach ($result as $row){
$employee=array('employeeid'=>$row['employeeid'],
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
$requests = $dbh->query(sprintf("SELECT * FROM employee_requests WHERE employee_id = '%s'", $row['employeeid']))->fetchAll(PDO::FETCH_ASSOC);
$employee['requests'] = requests;
$return[] = $employee;
}

关于PHP json_encode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com