title: How to assign key:value pairs from SQL to JavaScript Object using PHP?
body: <p>I have the following data in an SQL database</p>
  
  <pre><code>cname, ccode, colour
  Great Britain, GB, 1
  Italy, IT, 1
  France, FR, 1
  Spain, ES, 1
  </code></pre>
  
  <p>How can I create a JavaScript object like below?</p>
  
  <pre><code>var countries = {"GB":1, "IT":1, "FR":1, "ES":1}
  </code></pre>
  
  <p>So far, I have the following code;</p>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>$query2 = "SELECT ccode,colour FROM country_data WHERE 1";
  $result2 = mysql_query($query2);
  if (!$result2) {
    die('Invalid query: ' . mysql_error());
  }
  
  $rows2 = array();
    while($r2 = mysql_fetch_assoc($result2)) {
       $rows2[] = $r2;
  }
  </code></pre>
  
  <p><strong>JS</strong></p>
  
  <pre><code>var colours = '&lt;?php print json_encode($rows2); ?&gt;';
  </code></pre>
  
  <p>Which returns:</p>
  
  <pre><code>[{"ccode":"GB","colour":"1"},{"ccode":"IT","colour":"1"},{"ccode":"FR","colour":"1"},{"ccode":"ES","colour":"1"}]
  </code></pre>