I have a foreach loop that fetches values from mysql table. After fetching the values, their placed inside an array and then finally converted into a json object. The format of the json object has to be specific in order to work properly with third party api that I am currently using. The results I am getting currently placed all the values inside a json object. My goal is to pair values on separate json objects {},{},etc
. In addition, How can I add labels inside the object for the values that were fetch?
$level_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$level_query->execute();
$data = $level_query->fetchAll();
$level_data = array();
foreach ($data as $row) {
$type = $row["type"];
$level_data[$type] = $row["cnt"];
} // foreach ($data as $row) {
echo json_encode($level_data);
Current Format:
{" Expert":"12","Intermediate":"512","Beginner":”1002”}
Correct/Desired format Format:
{ level: "Expert", count: 12 },
{ level: "Intermediate", count: 512 },
{ level: "Beginner", count: 1002 }