我需要绘制一个未定义行数(行)的Google Chart。让我们假设我需要在某一天绘制两支球队的目标数量(例如,球队的数量是固定的,但可能是任何人,所有球队的天数都是相同的)。我有这个数组:
Array
(
[team1] => Array
(
[0] => Array
(
[day] => 1
[goals] => 3
)
[1] => Array
(
[day] => 2
[goals] => 1
)
[2] => Array
(
[day] => 3
[goals] => 0
)
)
[team2] => Array
(
[0] => Array
(
[day] => 1
[goals] => 1
)
[1] => Array
(
[day] => 2
[goals] => 2
)
[2] => Array
(
[day] => 3
[goals] => 4
)
)
)
我试过创建这个循环:
$resultArray = array();
$resultArray['cols'][] = array('label' => "Day", 'type' => 'string');
// $array is the one shown before
foreach($array as $key => $chartData){
$resultArray['cols'][] = array('label' => $key, 'type' => 'number');
foreach($chartData as $data){
$resultArray['rows'][] = array('c' => array( array('v' => $data['day']), array('v' => $data['goals'])));
}
}
问题在于图表只绘制了一行,两个团队的数据全部加在一起,而每个团队只有两行。
我真的很感激任何帮助。
答案 0 :(得分:1)
我认为你使用谷歌图表数据的关联数组会让自己变得更难。您的阵列的数据结构也为循环添加了一些挑战,使得以所需格式输出数据更具挑战性:
$chartData = array();
$chartData[] = array("Day");
foreach($array as $key => $a){
$chartData[0][] = $key;
for($i = 0; $i < count($a); $i++){
if(!is_array($chartData[$i+1])){
$chartData[$i+1] = array();
$chartData[$i+1][] = $a[$i]['day'];
}
$chartData[$i+1][count($chartData[0])-1] = $a[$i]['goals'];
}
}
这应该为您提供获得所需图表数据表所需的格式:
[
["Day","team1","team2"]
[1,3,1]
[2,1,2]
[3,0,4]
]
在天数(x轴)内为每个团队创建一个目标数量(y轴)的线。希望这有帮助