在PHP中使用变量来创建JSONTable

时间:2014-08-27 00:49:23

标签: php json google-visualization

我尝试从table gainfinal获取数据,并在Google API图表中以可视化方式显示JSON_Table中的数据。我特别使用了两个变量$ countryone和$ countrytwo。它们已在下面的代码中使用。其他一切都很好。代码的输出就像这样

{"cols":[{"label":"year","type":"string"},{"label":".$countryone.","type":"number"},{"label":".$countrytwo.","type":"number"}],"rows":[{"c":[{"v":"1995"},{"v":"76.8561073"},{"v":"46.8550182"}]},{"c":[{"v":"1996"},{"v":"77.0366637"},{"v":"47.1409752"}]},{"c":[{"v":"1997"},{"v":"77.180129"},{"v":"46.6331669"}]}

在第二和第三列中,我需要打印变量的实际值(我的意思是美国和NPL),但它只是将变量打印为字符串。我该如何纠正?

    <?php
    ini_set('display_errors', 1); 
    $username = "root"; 
    $password = "";   
    $host = "localhost";
    $database="climate";

    $countryone='USA'; 
    $countrytwo='NPL';
    $index ='gainfinal'; 


    $server = mysql_connect($host, $username, $password);
    $connection = mysql_select_db($database, $server);

    $myquery = "SELECT  `year`, 

        sum(case when `countrycode` = '$countryone' then `values` else 0 end) AS `countryone`,
        sum(case when `countrycode` = '$countrytwo' then `values` else 0 end) AS `countrytwo`

FROM   `$index`
GROUP BY `year`
";
    $query = mysql_query($myquery);
    $table = array();
    $table['cols'] = array(
    /* define your DataTable columns here
     * each column gets its own array
     * syntax of the arrays is:
     * label => column label
     * type => data type of column (string, number, date, datetime, boolean)
     */
    array('label' => 'year', 'type' => 'string'),
    array('label' => '.$countryone.', 'type' => 'number'),
    array('label' => '.$countrytwo.', 'type' => 'number'),


    // etc...
);
    $rows = array();
while($r = mysql_fetch_assoc($query)) {
    $temp = array();
    // each column needs to have data inserted via the $temp array
    $temp[] = array('v' => $r['year']);
    $temp[] = array('v' => $r['countryone']);
    $temp[] = array('v' => $r['countrytwo']);


    // etc...

    // insert the temp array into $rows
    $rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;

// encode the table as JSON
$jsonTable = json_encode($table);

// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

// return the JSON data
echo $jsonTable;
?>

1 个答案:

答案 0 :(得分:0)

您需要删除变量名称周围的单引号,或使用双引号。单引号不解析其中的变量,如双打do:

array('label' => 'year', 'type' => 'string'),
array('label' => $countryone, 'type' => 'number'),
array('label' => $countrytwo, 'type' => 'number'),

......或:

array('label' => 'year', 'type' => 'string'),
array('label' => "$countryone", 'type' => 'number'),
array('label' => "$countrytwo", 'type' => 'number'),

您目前的方式('.$countryone.')将其解释为字符串,从而导致'.$countryone.'。如果您将其更改为双引号,则您仍可获得任意一方的句号,例如.USA. ".$countryone."将解析变量的文字值。