从以下各项中提取值:{"参加":0," eventid":1," userid":1}在PHP中

时间:2016-03-27 21:13:57

标签: php arrays json

到目前为止,我已经尝试了几种从JAVA接收的以下数据中提取数据的方法(在print_r($ _ POST)之后):

{"attending":0,"eventid":1,"userid":1}

但我没有运气,因为我在SO和网络上发现的其他方式都略有不同(被''和[]包围)

我的代码:

print_r($_POST);
$data = json_decode($_POST);

$userid = $data['userid'];
$eventid = $data['eventid'];
$attending = $data['attending'];

我的问题是:如何正确地从Post中提取值并将它们分配给值?

我是PHP的新手,所以请不要粗鲁评论。

我也尝试过:

$data = json_decode($_POST, true);

如评论中所述,但现在我得到了:

Warning: json_decode() expects parameter 1 to be string, array given in C:\xampp\htdocs\attendanceradio.php on line 9

的var_dump($ _ POST);

Array
                                                          (
                                                              [{"attending":0,"eventid":2,"userid":1}] => 
                                                          )
                                                          array(1) {
                                                            ["{"attending":0,"eventid":2,"userid":1}"]=>
                                                            string(0) ""
                                                          }

完整的PHP代码:

<?php

    $user = 'root';
    $pass = '';
    $db = 'testuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');
    print_r($_POST['json']);
    var_dump($_POST);

    $json = json_decode(trim(key($_POST), '[]'), true);
        var_dump($json);
    $userid = $json['userid'];
    $eventid = $json['eventid'];
    $attending = $json['attending'];

    $statement = mysqli_prepare($con, 
    'INSERT INTO user_has_event(user_user_id, event_event_id, attendance)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE attendance = ?');

    mysqli_stmt_bind_param($statement, 'iii', $userid, $eventid, $attending);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $userid, $eventid, $attending);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:1)

根据您的数据,以下内容应该有效吗?

<?php

$json = json_decode(trim(key($_POST), '[]'), true);

var_dump($json);

?>

答案 1 :(得分:0)

给出了Array而不是字符串的错误消息,根据var_dump,我可以看到POST正在返回一个数组。

如果要解码JSON字符串,则必须指向添加字符串所在的数组索引,因此您的代码应如下所示:

$data = json_decode($_POST[0], true);

$userid = $data['userid'];
$eventid = $data['eventid'];
$attending = $data['attending'];