[英]PHP json_encode
This is my script at the moment: 这是我目前的脚本:
//... 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) .'';
This gives a result like: 结果如下:
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '001',
...,
...
}
]
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '002',
...,
...
}
]
But what i would like is a result like this (so each employee has one object with multiple requests): 但是我想要的是这样的结果(因此,每个员工都有一个带有多个请求的对象):
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'requests': [
{
'id': '001',
...,
...
},
{
'id': '002',
...,
...
}
]
}
]
Can someone help me with this? 有人可以帮我弄这个吗?
Thanks in advance, 提前致谢,
Jan 一月
You'll need to include the requests
records in each employee array: 您需要在每个员工数组中包括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;
}
Change your foreach
as follows: 如下更改您的foreach
:
foreach ($result as $row){
$employeeid = $row['employeeid'];
if (!isset($return[$employeeid]))
$return[$employeeid] = array(
'employeeid' => $row['employeeid'],
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'requests' => array()
);
$return[$employeeid]['requests'][] = array(
'id' => $row['id'],
'startdate' => $row['startdate'],
'enddate' => $row['enddate'],
'type' => $row['type'],
'reason' => $row['reason']
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.