doulin9679
2017-01-30 06:21
浏览 42

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
    
        }
    }
    
    打赏 评论

相关推荐 更多相似问题