title: Retrieve data from PHP file using $.getJSON
body: <p>I'm trying to set up a comments system on photos.</p>
  
  <hr>
  
  <p><strong>I understand how to use $.getJSON when the array is like this:</strong></p>
  
  <p>get.php:</p>
  
  <pre><code>$var = 5;
  echo json_encode(array('var'=&gt;$var));
  </code></pre>
  
  <p>main.php:</p>
  
  <pre><code>$.getJSON("get.php",function(data){
      number = data.var; // number = 5
  });
  </code></pre>
  
  <p>But I have a more complex thing.</p>
  
  <hr>
  
  <p>My <em>comments</em> table has these 4 columns: <strong>id | photo_id | comment | date</strong></p>
  
  <p>For example let's say we're trying to retrieve the comment data from the photo with </p>
  
  <p><code>photo_id == 1</code>. </p>
  
  <p>We don't know how many comments there might be.</p>
  
  <p>In getcomments.php:</p>
  
  <pre><code>$photoid = 1;
  
  $comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
  
  while($commentrow = $comment-&gt;fetch_assoc()) {
      $comments[] = $commentrow;
  }
  </code></pre>
  
  <p>Then you encode it:</p>
  
  <pre><code>echo json_encode($comments);
  </code></pre>
  
  <p>Which prints something like this (the photo has 2 comments):</p>
  
  <pre><code>[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
  </code></pre>
  
  <p><strong>How do I declare variables for the comments array?</strong></p>
  
  <pre><code>$.getJSON("getcomments.php",function(data){
      // how do I declare variables for the comments array, especially since you don't know how many there might be?
  });
  </code></pre>
  
  <hr>
  
  <p>Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. <code>echo json_encode(array('img1'=&gt;$img1link))</code> and <code>echo json_encode($comments);</code> need to be echoed within the same PHP file, but it made the code stop working altogether.</p>