本质上,我正在使用 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