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"
}
try this
foreach ($data as $row) {
$id=$row["id"];
$json_data[$id] =$row["name"];
}
The problem was that while defining the value in json_data in your foreach loop you are creating an array for every single value, so you are not getting the desired result.
change thisarray( $row["id"] => $row["name"]);
to$json_data[$row["id"] ] = $row["name"]
inside the for loop
foreach ($data as $row) {
$json_data[$row["id"] ] = $row["name"];
}
You will need to change your PHP code to create a normal single dimensional array, right now you are creating a multidimensional array. Your PHP should be like this:
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[$row["id"]] = $row["name"];
} // foreach ($data as $row) {
echo json_encode($json_data);
Notice the change in the foreach loop, we are no longer appending a new array onto the $json_data
array(which would create a multidimensional array). This will give you a single dimensional array with the proper key:value pairs. Then when you run the json_encode you will get your desired JSON format.