问题
i'm new to google apps script and i'm trying to visualize data using the Google Visualization API. I have been able to display a table from the good examples given on mixing php and html. But the database does not seem to have the right format for the column charts.
The table has the colums 'day' 'user' 'task' 'hours' and the data is then being pushed into the rows underneath by a while loop:
$table1 = array();
$table1['cols'] = array(
// Labels for your chart, these represent the column titles.
array('label' => 'day', 'type' => 'string'),
array('label' => 'user', 'type' => 'string'),
array('label' => 'task', 'type' => 'string'),
array('label' => 'hours', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['day']);
$temp[] = array('v' => $r['user']);
$temp[] = array('v' => $r['task']);
$temp[] = array('v' => $r['hours']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table1['rows'] = $rows;
giving me a table like this:
day user task hours
monday user1 wash 3
monday user2 clean 2
monday user3 iron 4
tuesday user1 clean 4
tuesday user2 iron 1
tuesday user3 wash 3
What i actually need is a table like this:
day user1 user2 user3 clean iron wash
monday 3 2 4 2 4 3
tuesday 4 1 3 4 1 3
I know the list of users in advance.
EDIT: The issue is '(server side) cross tabulation' as i'm seeing in this link. I'm trying to figure it out and would still be glad for every help and will of couse mark answers as such. Thanks!
回答1:
To get the format you need, the easiest way is to pivot your data in the MySQL query. MySQL doesn't support pivots, but you can fake it like this:
SELECT
day,
SUM(IF(user = 'user1', hours, 0)) as user1,
SUM(IF(user = 'user2', hours, 0)) as user2,
SUM(IF(user = 'user3', hours, 0)) as user3,
SUM(IF(task = 'clean', hours, 0)) as clean,
SUM(IF(task = 'iron', hours, 0)) as iron,
SUM(IF(task = 'wash', hours, 0)) as wash
FROM myTable
GROUP BY day
Then build your DataTable with a column for each user and task:
$table1 = array(
'cols' => array(
array('label' => 'day', 'type' => 'string'),
array('label' => 'user1', 'type' => 'string'),
array('label' => 'user2', 'type' => 'string'),
array('label' => 'user3', 'type' => 'number'),
array('label' => 'clean', 'type' => 'number'),
array('label' => 'iron', 'type' => 'number'),
array('label' => 'wash', 'type' => 'number')
),
'rows' => array()
);
while($r = mysql_fetch_assoc($result)) {
$table1['rows'][] = array('c' => array(
array('v' => $r['day']),
array('v' => $r['user1']),
array('v' => $r['user2']),
array('v' => $r['user3']),
array('v' => $r['clean']),
array('v' => $r['iron']),
array('v' => $r['wash'])
));
}
来源:https://stackoverflow.com/questions/24743627/google-visualization-api-format-mysql-result-with-cross-tabulation