PHP json_encode

时间:2014-11-21 13:27:28

标签: php mysql json pdo

这是我的剧本:

 //... 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',
                ...,
                ...
            }
        ]
    }
]

有人可以帮我这个吗?

提前致谢,

2 个答案:

答案 0 :(得分:0)

您需要在每个员工数组中包含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;
 } 

答案 1 :(得分:0)

按如下方式更改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']
    );
}