Essentially, I'm using pdo to run the following query and format the results into JSON. The problem is that I need column2 to always appear as a string in JSON, even if the value is a number, without reformatting the other column values, so I'm trying to do a for loop to convert using 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); ?>
Current JSON response:
[ { "column1": "tree", "column2": 29012, "column3": "foggy" }, { "column1": "tree", "column2": 00930239, "column3": "sunny" }, { "column1": "tree", "column2": 203943, "column3": "rainy" } ]
Ideal JSON response:
[ { "column1": "tree", "column2": "29012", "column3": "foggy" }, { "column1": "tree", "column2": "00930239", "column3": "sunny" }, { "column1": "tree", "column2": "203943", "column3": "rainy" } ]
You can try it,
ATTR_STRINGIFY_FETCHES
Reference:https://www.php.net/manual/en /pdo.setattribute.php
phpfiddle