0

Can't seem to figure out how to access a JSON object within an array in my for loop. Any help would be great. Json:

[
 {
  subject: "******",
  subscribers_primary_advisor_id: "******",
  comments_first: "******",
  created_at: "*******",
  discussion_category: "*****",
  last_comment_by: "******",
  last_comment_by_id: "*******",
  updated_at: "*******"
 },

Here is my php:

for($j = 0; $j < $size; $j++){
$sql = "INSERT INTO advisor_discussion(`comment_subject`,`advisor_id`,`content`,`date_created`,`discussion_category`,`
last_comment_id`,`updated_at`) VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssssss', $comment_subject, $advisor_id, $content, $date_created, $discussion_category, $last_comment_id, $updated_at);

$comment_subject = $discussion['subject'][$j];
$advisor_id = $discussion['subscribers_primary_advisor_id'][$j];
$content = $discussion['comments_first'][$j];
$date_created = $discussion['created_at'][$j];
$discussion_category = $discussion['$discussion_category'][$j];
$last_comment_id = $discussion['last_comment_by_id'][$j];
$updated_at = $discussion['updated_at'][$j];

if ($stmt->execute() !== TRUE) {
  var_dump($stmt);
  die("Error inserting discussion");
}

}

1
  • 2
    Your JSON data contains a JavaScript array with objects, you should access each object by refering to an index in the array. So it would be $discussion[$j]['subject'] and so on. I expect that your $size variable contains count($discussion); Commented Feb 1, 2018 at 23:04

1 Answer 1

2

Assuming that you have parsed the JSON with json_decode function and you have multiple JS objects contained in your JSON string then perhaps instead of $discussion['subject'][$j] do $discussion[$j]['subject'] .

In other words the index first and then the JS object property.

Also note that json_decode can create PHP objects too. See here about the second parameter: http://php.net/manual/en/function.json-decode.php

If you do not specify that you want an associative array then you might want to try doing $discussion[$j]->subject instead as you will get an array of objects.

Sign up to request clarification or add additional context in comments.

2 Comments

I get an undefined index when I try it both ways, so I don't think its parsing through the data in the for loop with the increment in front of it. Any other suggestions?
have you tried accessing it as object property? I mean like $discussion[$j]->subject - it might be that your JSON objects were parsed as PHP standard objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.