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 }
Try this:
$output = array();
foreach ($data as $row) {
array_push($output, array('level'=>$row["type"], 'count'=>$row["cnt"]));
}
echo json_encode($output);
The desired format looks like a array of objects, each of which contains a level
and a count
property.
Data like this:
$data = array(
array('type'=>'a','cnt'=>1),
array('type'=>'b','cnt'=>2),
array('type'=>'c','cnt'=>3),
array('type'=>'d','cnt'=>4),
array('type'=>'e','cnt'=>5)
);
Comes out like this:
[{"level":"a","count":1},{"level":"b","count":2},{"level":"c","count":3},{"level":"d","count":4},{"level":"e","count":5}]