Search code examples
javascriptphparraysdatabasedrupal-7

How can i print a database query to a javascript array?


I want to display some information in a jvector map and get the information out of the database with these code:

$query = db_select('location', 'l')
    ->condition('l.lid', 0, '<>')
    ->fields('l', array('country'))
    ->range(0, 50);

$result = $query->execute();
$arr = [];

while($record = $result->fetchAssoc()) {
      $arr[] = $record;       
}
print_r($arr);

For the fields i use the location modul in Drupal 7 and i get these array:

Array ( 
    [0] => Array ( 
        [country] => de 
    ) 
    [1] => Array ( 
        [country] => de 
    ) 
    [2] => Array ( 
        [country] => fr 
    ) 
)

But, how can i take out these information, count the countries and display it as a javascript display like: var gdpData = { "de": 2, "Fr": 1, ... }; for the jvector map?


Solution

  • You can use the wrapper function drupal_json_encode for Drupal 7.

    Or alternatively, you can pass the PHP $arr variable to drupal_add_js(array('locations' => $arr), 'setting'); and access it as follows in javascript:

    var gdpData = Drupal.settings.locations;