本質上,我正在使用 pdo 運行以下查詢並將結果格式化為 JSON。問題是我需要 column2 始終在 JSON 中顯示為字串,即使該值是數字,也不需要重新格式化其他列值,因此我嘗試執行 for 循環以使用 strvalue 進行轉換。
$stmt = $pdoConnect->prepare(' SELECT column1, column2, column3 from table1 where column1 = "tree" '); $stmt->execute([]); $row = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($row as $rowvalue) { strval($rowvalue["column2"]); } echo json_encode($row); ?>
目前 JSON 回應:
[ { "column1": "tree", "column2": 29012, "column3": "foggy" }, { "column1": "tree", "column2": 00930239, "column3": "sunny" }, { "column1": "tree", "column2": 203943, "column3": "rainy" } ]
理想的 JSON 回應:
[ { "column1": "tree", "column2": "29012", "column3": "foggy" }, { "column1": "tree", "column2": "00930239", "column3": "sunny" }, { "column1": "tree", "column2": "203943", "column3": "rainy" } ]
您可以嘗試一下,
ATTR_STRINGIFY_FETCHES
參考:https://www.php.net/manual/en /pdo.setattribute.php
phpfiddle
#