PHP:如何解析JSON数据

时间:2018-03-20 17:42:04

标签: php mysql json parsing

我正在尝试将JSON数据发送到PHP服务器,但我可以理解如何在PHP中解析我的JSON并在Mysql数据库中插入值。

以下是查看我的JSON数据的方法

 {"reps_list":{"selected_subcategory_id":[0,1,2]}}

这是我的PHP代码:

$reps_list = $_POST['reps_list'];
$reps_list= json_decode($reps_list,TRUE);

 for($i = 0; $i <= count($array['reps_list']['selected_subcategory_id']); $i++){
mysqli_query($conn, "INSERT INTO reps VALUES(NULL, '".$array['reps_list']['selected_subcategory_id'][i]."', 1, 1 )");

}

任何建议?

3 个答案:

答案 0 :(得分:2)

对您的有效 json尝试这样做,使用json_decode使用第二个参数 true 将字符串解析为array以使其成为数组,然后在数据库查询中使用它之前将其视为数组。

$array = json_decode('{"reps_list":{"selected_subcategory_id":[0,1,2]}}',1);
echo "Main Array after json string decode \n\n";
print_r($array); 
echo "\n\n";
echo "Access selected_subcategory_id \n\n";
print_r($array['reps_list']['selected_subcategory_id']);

<强>输出:

json字符串解码后

主数组

Array
(
    [reps_list] => Array
        (
            [selected_subcategory_id] => Array
                (
                    [0] => 0
                    [1] => 1
                    [2] => 2
                )

        )

)

访问 selected_subcategory_id

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)

DEMO https://eval.in/975261

答案 1 :(得分:1)

由于您已将帖子INSERT更新到数据库中,因此您可以使用以下内容:

$reps_list = $_POST['reps_list'];
$json = json_decode($reps_list,TRUE);

$arr = $json['reps_list']['selected_subcategory_id'];

$insertWorkout = $mysqli->prepare("INSERT INTO reps (column1, column2, column3) VALUES (?, ?, ?)");
$insertWorkout->bind_param("iii", $arr[0], $arr[1], $arr[2]); // iii means they are all integers
$insertWorkout->execute();

答案 2 :(得分:0)

您可以使用

foreach($reps_list['selected_subcategory_id'] as $key => $value){

mysqli_query($conn, "INSERT INTO reps VALUES(NULL, '".$value."', 1, 1 )");

}