PHP JSON动态存储在数据库中

时间:2017-01-30 06:21:08

标签: php json

我得到{"1":["77","77"],"2":["33","55","66"]}作为JSON

我在PHP中将其解码为$organize = json_decode($json);

现在要在数据库中存储值我正在做类似

的事情
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) {

    } 
}

从上面的json输出中专门输入$organize->(1) and $organize->(2)

有没有办法检索键“1”和& “2”或任何数字,所以我把一个forloop outsite我的主要forloop并自动存储每个数据。

这样的东西
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) {

    } 
}
}

有没有办法让它像这样动态。

谢谢。

1 个答案:

答案 0 :(得分:1)

将字符串解码为数组并使用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

    }
}

正如在评论中正确注意到的那样,即使将字符串解码为对象也会得到相同的结果:

$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

    }
}