1

my json result from the mysqlquery in the php-file looks something like this: [{"ID":1,"comment":"Hello"},{"ID":2,"comment":"SecondHello"}] For my purpose I need the IDs also as a String. I cannot/do not want to change the datatype in the database. What do I have to change in my php file or in the Sql query to get the ID as a String.

 <?php
     $host = '';
     $db   = '';
     $user = '';
     $pass = '';
     $charset = 'utf8mb4';

     $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
     $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
     ];
     $pdo = new PDO($dsn, $user, $pass, $opt);


     $sql= SELECT * FROM orders

     $resultArray = array();
     $tempArray = array();
     foreach ($pdo->query($sql) as $row) {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
      }
     echo json_encode($resultArray);
    ?>`

3 Answers3

2

You can make sure that each row as you add it in is converted using strval...

 foreach ($pdo->query($sql) as $row) {
    $tempArray = array_map('strval', $row);    // Convert all columns to strings
    array_push($resultArray, $tempArray);
  }

Adds an overhead as this is applied to all columns, but it saves individual column by column processing (especially when the SQL changes)

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

what about this piece of code

$resultArray = array();
$tempArray = array();
foreach ($pdo->query($sql) as $row) {
    $fields = json_decode($row["jsonFieldName"],1);//decode your json string
    foreach($fields as $key=>$field){// read each object..
      $field["ID"] = strval($field["ID"]);// change the id property to str
      $fields[$key] = $field;// update decoded array
    }
    $row["jsonFieldName"] = json_encode($fields);//encode array and update value
    array_push($row, $row);

}

It may help you, but it is not a good way to do.

Phoenix404
  • 898
  • 1
  • 14
  • 29
1

You can use array_map to crawl your array and cast each element to string with strval

foreach ($pdo->query($sql) as $row) {
    $tempArray = array_map('strval', $row);
    array_push($resultArray, $tempArray);
}
plmrlnsnts
  • 1,644
  • 12
  • 10