doulin9679 2017-01-30 06:21
浏览 46
已采纳

PHP JSON动态存储在数据库中

I am getting {"1":["77","77"],"2":["33","55","66"]} as JSON

Which I am decoding in PHP as $organize = json_decode($json);

Now to store value in database I am doing something like

foreach($organize->{1} as $pos => $div){

$pos1 = 1;
    $sql = "INSERT INTO process VALUES (DEFAULT,'".mysqli_real_escape_string($conn,$pos1)."','".mysqli_real_escape_string($conn,$div)."')";
    if ($conn->query($sql) === TRUE) {

    } 

}

foreach($organize->{2} as $pos => $div){

    $pos1 = 2;
    $sql = "INSERT INTO process VALUES (DEFAULT,'".mysqli_real_escape_string($conn,$pos1)."','".mysqli_real_escape_string($conn,$div)."')";
    if ($conn->query($sql) === TRUE) {

    } 
}

Where $organize->(1) and $organize->(2) are specifically entered from the json output above

Is there way to retrieve the keys "1" & "2" or any number so I put a forloop outsite my main forloop and it automatically stores for every data.

Something like

foreach(ACCESS KEYS HERE)
foreach($organize->{$KEY NUMBER HERE} as $pos => $div){

    $pos1 = $KEY NUMBER HERE;
    $sql = "INSERT INTO process VALUES (DEFAULT,'".mysqli_real_escape_string($conn,$pos1)."','".mysqli_real_escape_string($conn,$div)."')";
    if ($conn->query($sql) === TRUE) {

    } 
}
}

Is there a way to make it dynamic like that.

Thank You.

  • 写回答

1条回答 默认 最新

  • douaonong7807 2017-01-30 06:23
    关注

    Decode string to array and iterate with foreach:

    $organize = json_decode($json, true);  // will give you array
    foreach ($organize as $pos => $level1) {
        foreach ($level1 as $value) {
            // insert value here
            // $pos is key, $value is value
    
        }
    }
    

    As rightly noticed in comments, even decoding string to object will give you same results:

    $organize = json_decode($json);  // no second argument
    foreach ($organize as $pos => $level1) {
        foreach ($level1 as $value) {
            // insert value here
            // $pos is key, $value is value
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊