简体   繁体   中英

PHP and MYSQL - how can i get json output from my sql with array?

i want to get values in json, but i have duplicate values in name_exercise and photo_exercise column, i would like to know how to solve this problem... SQL below

  $idTreino = $_POST['id_treino'];
  
$sql = $pdo->query("SELECT name_exercise, photo_exercise, rep_exercise as rep,load_exercise as load, time_exercise as time,
e.name_exercise,e.photo_exercise FROM serie CROSS JOIN
exercise_training as et ON serie.FK_exercise_training =
et.id_exercise_training CROSS JOIN exercise as e ON e.id_exercise =
et.FK_exercise WHERE FK_training = '".$idTraining."')->fetchAll(PDO::FETCH_CLASS);

how can i have a json output from my sql equal to the one below?

{"name_exercise":"supino","photo_exercise":"link",
"serie":[{"rep":30, "load": 20, "time":30}]
}

Directly from SQL your could not, but after fetching data in PHP, you can convert data to object

<?php
// Here the query
$sth = $dbh->prepare("SELECT name, age FROM players");
$sth->execute();
// Then fetch data
$data = $sth->fetchAll();
// And convert to object
$option1 = json_encode($data);
$option2 = (object) $data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM