duanmiaosi0150 2014-01-10 08:15
浏览 209
已采纳

在json对象中格式化值 - json_encode()

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 }
  • 写回答

1条回答 默认 最新

  • doutu6616 2014-01-10 08:18
    关注

    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}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号