doushu8260 2014-07-26 04:22
浏览 16
已采纳

解码json响应并为每个插入使用

<?php
$string ='{"type":"Text","totalprice":"0.05","totalgsm":"6","remaincredit":"63.6433","messages": [
        {"status":"1","messageid":"157157","gsm":"9211111111111"},
        {"status":"1","messageid":"157154","gsm":"9211111111112"},
        {"status":"1","messageid":"157151","gsm":"9211111111113"},
        {"status":"1","messageid":"157149","gsm":"9211111111114"},
        {"status":"1","messageid":"157142","gsm":"9211111111115"},
        {"status":"1","messageid":"157130","gsm":"9211111111116"}
        ]}';
?>

I want to get:

type            = text
totalprice      = 0.05
totalgsm        = 6
remainingcredit = 63.6433

status=1 messageid=157157 gsm=9211111111111
status=1 messageid=157157 gsm=9211111111112
status=1 messageid=157157 gsm=9211111111113
status=1 messageid=157157 gsm=9211111111114

I want to insert in MYSQLDB in 2 queries:

First INSERT Query for type = text, totalprice = 0.05, totalgsm = 6, remainingcredit = 63.6433

Second INSERT Query for messages array Using foreach to insert all given

status=1 messageid=157157 gsm=9211111111111
status=1 messageid=157157 gsm=9211111111112
status=1 messageid=157157 gsm=9211111111113
status=1 messageid=157157 gsm=9211111111114

Please Guide me how to decode this type of json response and how to parse to insert in DB?

  • 写回答

3条回答 默认 最新

  • duanjianqu3685 2014-07-26 04:47
    关注

    May this way you have to do:

    $string = json_decode('{"type":"Text","totalprice":"0.05","totalgsm":"6","remaincredit":"63.6433","messages": [
        {"status":"1","messageid":"157157","gsm":"9211111111111"},
        {"status":"1","messageid":"157154","gsm":"9211111111112"},
        {"status":"1","messageid":"157151","gsm":"9211111111113"},
        {"status":"1","messageid":"157149","gsm":"9211111111114"},
        {"status":"1","messageid":"157142","gsm":"9211111111115"},
        {"status":"1","messageid":"157130","gsm":"9211111111116"}
        ]}', true);
    
    $type = $string['type'];
    $totalprice = $string['totalprice'];
    $totalgsm = $string['totalgsm'];
    $remaincredit = $string['remaincredit'];
    
    /** Insert using First Query **/
    
    /** Now for message array **/
    foreach ($string['messages'] as $key => $msg) {
        $status = $msg['status'];
        $msg_id = $msg['messageid'];
        $gsm = $msg['gsm'];
        /*** Insert using your second query ***/
        /** ------------------------ **/
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名