dongmao3131 2016-06-25 06:01
浏览 28
已采纳

使用php高效地在json对象中创建一个json对象[关闭]

I'm trying to make a json object inside the json object. The json object I desire to make is:

{"post1" : {"id" : "1", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
 "post2" : {"id" : "2", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
 "post3" : {"id" : "3", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
 "post4" : {"id" : "4", "brand" : "brandFromQuery", "model" : "modelFromQuery"}}"

What I ultimately want to do is create a json object as you see above and pass it along to the front end. And the data is the result of SQL query. Each "inner" json object is fetched from the query. Any tip on how I should create this? Would love some efficient solutions for this. I was thinking of doing for loop in a for loop but concerned about the efficiency.

EDIT: I'm trying to use json_encode to achieve this but i'm not sure how to implement this. what i have tried so far is 1) Create JSON object using PHP (creates a class and inputs the data). I really like this method because it is creating a separate class so its more modular but i just cant seem to find a way to create 4 different posts.

  • 写回答

1条回答 默认 最新

  • dtd14883 2016-06-25 06:06
    关注

    If each inner object is a result-set from the SQL query then you just need single for-loop to create kind of JSON string.

    Create main array

    $main_array=array();
    

    Now iterate over result from MySQL like this and append them in main array.

    /* Your MySQL logic to fetch result */
    $count=1;
    while($row = $result->fetch_assoc()) { // assuming fetch method, you can replace it with yours.
         $main_array["post".$count]=$row;
         $count++;
    }
    
    $json_string=json_encode($main_array);
    

    I think this is the best solution in which you can create the required JSON string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题