1

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?

Kevin
  • 41,694
  • 12
  • 53
  • 70
Bruno
  • 125
  • 6

2 Answers2

2

json_encode — Returns the JSON representation of a value

json_encode($arr);

Sample :

while($record = $result->fetchAssoc()) {
    if (isset($arr[$record["country"]])) {
        $arr[$record["country"]]++;
    } else {
        $arr[$record["country"]] = 0;
    }
}

json_encode($arr);

In javascript :

JSON.parse(data);
console.log(data.de); //2
user2226755
  • 12,494
  • 5
  • 50
  • 73
  • Wow thanks, i try it as soon as possible! Why did you get an negative vote? – Bruno Jul 26 '14 at 14:28
  • I don't know, my answer works ? – user2226755 Jul 27 '14 at 15:27
  • I'd warrant a guess for your -1 being somebody doesn't like your coding style, but I'll +1 because it works. – Darren Jul 28 '14 at 02:50
  • i get an error: SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help) [0] => de Maybe i do something wrong: – Bruno Jul 31 '14 at 21:35
  • You mix php and js... – user2226755 Aug 01 '14 at 13:54
1

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;

  • Great Thanks! I use drupal_add_js(array('location' => array_count_values($arr)), 'setting'); and i get what i want: Object { de=2, fr=1} very nice! – Bruno Jul 31 '14 at 21:21