2015-06-17 91 views
1

我正在使用json_encode()從MySQL中檢索數據。更改json_encode()輸出結構

$sq ="SELECT physics, chemistry, agriculture FROM subjects WHERE student = :student"; 
$stmt = $getdb->prepare($sq); 
$stmt->execute(array(':student'=>"123456")); 
$rslt = $stmt->fetchAll(); 

$sd=array(); 
foreach($rslt as $val){ 
    $sd[] = $val; 
} 
echo json_encode($sd); 

這是當期的輸出數據結構

array(
    array(
     "0" => 97, 
     "1" => 38, 
     "2" => 73, 
     "physics" => 97, 
     "chemistry" => 38, 
     "agriculture" => 73, 
    ) 
); 

我怎麼輸出上述這樣的:

array(
    array(
     "physics" => 97, 
     "chemistry" => 38, 
     "agriculture" => 73, 
    ) 
); 
+2

$ rslt的值是多少? – Ashwani

+0

如果$ rslt來自數據庫,它可能是數據庫返回值的方式。 – Thomas

+0

@Ashwani:謝謝我編輯了我的帖子。請查閱。 – Becky

回答

0
$stmt->fetchAll(PDO::FETCH_ASSOC) 

之前執行 這迫使PDO只使用聯想表示。