我的JSON数据变量为空


My JSON data variables are empty

我有JSON数据,为了调试目的,我手动设置了这些数据。我正试图将数据存储到它们自己的变量中(用于以后的DB存储),但它们是空的。

我试过两种不同的东西,但当echo把它们拿出来时,它仍然显得很空。有没有更好的方法可以做到这一点,并且可以将数据实际存储在所需的变量中?

$json = '[{
    "q1":"a",
    "q2":"d"
    }]';
$questions = json_decode($json, true);
$q1 = $questions->q1; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;

去掉json字符串周围的方括号:

$json = '{
  "q1":"a",
  "q2":"d"
}';
$questions = json_decode($json, true);
$q1 = $questions['q1']; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;

编辑:既然你打算通过AJAX发送信息,比如说使用

JSON.stringify($('#formId').serializeArray());

根据你最初的帖子,你可能会得到一个JSON数组。在这种情况下,你可能想做一个for循环,或者像这样直接访问问题:

$json = '[{
  "q1":"a",
  "q2":"d"
}]';
$questions = json_decode($json, true);
foreach($questions as $question) {
  $q1 = $question['q1']; //first method of getting the data
  $q2 = $question['q2']; //second attempted method
}
// This would also work:
echo $questions[0]['q1'];