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:
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 ($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']
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.