好的我需要帮助从php数组创建一个谷歌条形图。 这是我的数组
array (size=2)
0 =>
object(stdClass)[42]
public 'nombre' => string 'Anillo Princess' (length=15)
public 'total' => string '5' (length=1)
1 =>
object(stdClass)[43]
public 'nombre' => string 'Shake Sabor Vainilla' (length=20)
public 'total' => string '1' (length=1)
这是生成图表的代码
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Producto', 'Cantidad'],
["Anillo princess", 4],
["Shake Sabor Vainilla", 1],
["Colageno hidrolisado", 12],
["Proteina lifeone", 10],
['otros', 3]
]);
var options = {
title: 'Productos mas vendidos',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'Cantidad vendidas' },
axes: {
x: {
0: { side: 'top', label: 'Productos'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
</script>
如何将变量传递给脚本以使用数组中的值生成图表。
寻求帮助的人!
欢呼声。
答案 0 :(得分:1)
继承人尝试:
<?
//original array
$arr = [
['nombre' => 'Anillo Princess', 'total' => '5'],
['nombre' => 'Shake Sabor Vainilla', 'total' => '1']
];
//loop and build output array
$output = [["Producto", "Cantidad"]];
foreach($arr as $row) {
$output[] = [$row['nombre'], $row['total']];
}
//echo the result
echo json_encode($output);
?>
如果您只想在代码中回显数组,请执行以下操作:
var data = new google.visualization.arrayToDataTable(<?=json_encode($output)?>);
但您可以使用ajax请求加载数据