I am fetching values from mysql table. I am then placing the values inside an array and using th php built function json_enconde
to convert these values into a json format. I am getting results back but not in the desired format. In the php code you will notice I am using array and fetching values with a foreach
loop to place all values inside. As a result I am getting back several json objects. How can I get back just one json object with the corresponding values?
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[] = array(
$row["id"] => $row["name"]
);
} // foreach ($data as $row) {
echo json_encode($json_data);
Results:
{
1: "Item1"
},
{
2: "Item2"
},
{
3: "Item3"
}
Desired Results:
{
"1":"Item1",
"2":"Item2",
"3":"Item3"
}