2014-11-21 99 views
0

這是我此刻的腳本:PHP json_encode

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

有人可以幫助我嗎?

由於提前,

+1

你的循環是什麼? – Brewal 2014-11-21 13:30:08

+0

那麼你需要在那條路上構建你的數組。 – vaso123 2014-11-21 13:30:10

+0

並請顯示您的查詢。 – vaso123 2014-11-21 13:30:53

回答

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; 
} 
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'] 
    ); 
}