簡體   English   中英

更改json_encode()輸出結構

[英]Changing json_encode() output structure

我正在使用json_encode()從MySQL檢索數據。

$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,
    )
);
$stmt->fetchAll(PDO::FETCH_ASSOC)

執行之前這將強制PDO僅使用關聯表示。

從mysql獲取行時,您已經使用了http://php.net/manual/en/function.mysql-fetch-array.php或同等功能。 這使其成為數字索引和字符串索引。 使用mysql_fetch_assoc或http://php.net/manual/en/mysqli-result.fetch-assoc.php ,它們將僅返回帶有字符串索引的數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM