我试图从表gainfinal中获取数据,并在JSON_table中显示数据,以便在google API图表中进行可视化。我特别使用了两个变量$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"}]}
在第二列和第三列中,我需要打印变量的实际值(我的意思是,USA和NPL),但它只是将变量打印为I字符串。我该如何更正?
<?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;
?>
您需要删除变量名周围的单引号,或者使用双引号。单引号不像双引号那样解析其中的变量:
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."
会解析变量的文字值。