JavaScript和JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:

var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};

how to get the JSON array value to JavaScript Array. i just tried but it doesn't work. please some suggestions. here is my javascript array

for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;

}

As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.

Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:

<?php

    $results = $query->result(); // get results

    function m($v) { // a helper function for `array_map`
        return array('label' => $v->district_name, 
                     'data' => $v->countid);
    }

    $data = array('items' => array_map('m', $results));

?>

var data = <?php echo json_encode($data); ?>

*: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.

You really oughtn't think too hard about this. PHP does a fine job of serializing arrays as JSON.

var data = {
  items: <?php
    $arr = array();
    foreach($query->result() as $row) {
      $arr[] = array('label' => $row->district_name,
                     'data'  => $row->countid);
    }
    echo json_encode($arr);
    ?>
};

[insert same disclaimer as above about how you're really trying to create a JavaScript object]

This is JSON:

var foo = "{bar: 1}";

This is not JSON:

var foo = {bar: 1};

Your code snippet is not using JSON at all and my educated guess is that you don't even need it. If you are using PHP to generate some JavaScript code, you can simply tweak your PHP code to print text that will contain real JavaScript variables. There is no need to encode stuff as plain text!

Now it's clear we don't need JSON, let's use a dirty trick. PHP has json_encode() and we can abuse the fact that a JSON strings resemble JavaScript variables. All we have to do is call json_encode() on our PHP variable and forget to quote the result:

<?php

$foo = array(
    'bar' => 1,
    'dot' => FALSE,
);

echo 'var JSONString = "' . json_encode($foo) . '";' . PHP_EOL;
echo 'var realVariable = ' . json_encode($foo) . ';' . PHP_EOL;

Compare:

var JSONString = "{"bar":1,"dot":false}";
var realVariable = {"bar":1,"dot":false};

Edit: Yep, my JSONString is not a valid string... but we get the idea <:-)