druybew06513 2013-04-19 21:51
浏览 184
已采纳

将嵌套数组从json响应插入mysql

I have the following JSON response received from the client:

{
    "name": "Joel",
    "cities_visited": [{
        "city1": "Chicago",
        "city2": "Seattle"
    }],
    "active": true
}

I am using json_decode to get the results but having problems inserting the cities_visited as one single set of data into mysql. I have also tried with json_decode($json, true) with no luck.

Can anyone give me some insight how to get this data formatted properly prepared so i can insert into my db?

I need to somehow get this cities_visited array into one entry row on mysql and then be able to get it out and return it as the same with json_encode

  • 写回答

2条回答 默认 最新

  • dongyu6276 2013-04-19 21:56
    关注

    If you have only one column for cities_visited and you need to put multiple values into it, then they need to be serialized somehow. Since you're dealing with JSON already you might as well turn it back into json to send it to the database.

    $user = json_decode($input);
    $user->cities_visited = json_encode($user->cities_visited);
    

    Something like that. This isn't the best solution though, what you really want to do is create a many-to-man relationship between users and cities

    Users

    • id (int)
    • name (string)
    • status (string)

    Cities

    • id (int)
    • name (string)

    Visits

    • user_id (int)
    • city_id (int)

    And so in the example data you have above, you would create one row in the user table for Joel, two rows in the City table for Chicago and Seattle, and two rows in the Visits table that link them together.

    The advantage to this approach is that it is much easier to analyze the data now. Let's say you want to know what city has been visited the most? Simply

    select count(*) AS number_visits, name as city_name
    from Visits v 
    join Cities c on v.city_id = c.id
    group by v.city_id
    order by visits
    limit 1
    

    If the cities_visited field is serialized in the database, you have to loop through each user with PHP and count the results up yourself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?