DT.DTDG
DT.DTDG

Reputation: 765

My JSON data variables are empty

I have JSON data being fed in which I have set manually for debugging purposes. I'm trying to get the data to be stored in to their own variables (for later DB storage), however, they are empty.

I have tried 2 different things yet it's still appearing as empty when echo'ing them out. Is there a better way of doing this and one that will actually store the data in the required variables?

$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;

Upvotes: 0

Views: 52

Answers (1)

Jonathan
Jonathan

Reputation: 6537

Get rid of the square braces around the json string:

$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;

Edit: Since you are planning on sending the information over AJAX, say using something like

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

you may end up with an JSON array, as per your original post. In that case, you may want to do a for loop, or access the question directly like so:

$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'];

Upvotes: 2

Related Questions