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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置