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?

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Wow thanks, i try it as soon as possible! Why did you get an negative vote?
I don't know, my answer works ?
I'd warrant a guess for your -1 being somebody doesn't like your coding style, but I'll +1 because it works.
i get an error: SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help) [0] => de Maybe i do something wrong: <script> <?php $output = drupal_json_encode(array_count_values($arr)); ?> JSON.parse($output); console.log($output.de); </script>
You mix php and js...
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;

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.