使用PHP为Google图表格式化JSON文件
我正试图从我的数据库中获取信息到谷歌图表中。 要做到这一点,我需要根据谷歌的规范(在这里找到)格式化一个JSON文件 它需要按照以下示例进行格式化:使用PHP为Google图表格式化JSON文件,php,json,google-visualization,Php,Json,Google Visualization,我正试图从我的数据库中获取信息到谷歌图表中。 要做到这一点,我需要根据谷歌的规范(在这里找到)格式化一个JSON文件 它需要按照以下示例进行格式化: { cols: [ {label: 'NEW A', type: 'string'}, {label: 'B-label', type: 'number'}, {label: 'C-label', type: 'date'} ], rows: [ {c:[
{
cols: [
{label: 'NEW A', type: 'string'},
{label: 'B-label', type: 'number'},
{label: 'C-label', type: 'date'}
],
rows: [
{c:[
{v: 'a'},
{v: 1.0, f: 'One'},
{v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}
]},
{c:[
{v: 'b'},
{v: 2.0, f: 'Two'},
{v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}
]},
{c:[
{v: 'c'},
{v: 3.0, f: 'Three'},
{v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}
]}
]
}
然而,当我试图实现这一点时,我没有得到完全相同的JSON。
我的PHP代码:
$result = mysqli_query($dbConnection, $sql);
$json['cols'][] = array("label" => "year-week", "type" => "string");
$json['cols'][] = array("label" => "# non-bundle games given", "type" => "number");
$json['cols'][] = array("label" => "Users joined", "type" => "number");
$json['cols'][] = array("label" => "Users left", "type" => "number");
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$json['rows'][]['c'] = array_values($row);
}
}
// CLOSE CONNECTION
mysqli_close($dbConnection);
echo json_encode($json);
这给了我以下信息:
{
"cols": [
{
"label": "year-week",
"type": "string"
},
{
"label": "# non-bundle games given",
"type": "number"
},
{
"label": "Users joined",
"type": "number"
},
{
"label": "Users left",
"type": "number"
}
],
"rows": [
{
"c":
[
"201431",
"3",
"45",
"1"
]
},
{
"c":
[
"201432",
"3",
"0",
"1"
]
}
]
}
如您所见,行部分不正确。
我尝试了几种方法来构建PHP代码,但现在我只是在猜测。
关于如何根据Google的规范编写PHP代码以输出,有什么建议吗?使用PHP创建一个列表,列出将传递给图形的任何值数组。传递给API进行绘图的JSON不会让您的代码中有空格,因此循环遍历结果,然后最终内爆,并在方法中返回所有结果。。酪蛋白点
function prepMyGraphValues(){
//Initialize here
$myData = [];
//Do SQL stuff here
$sql = ...
//Have a counter
$count = 0;
//Loop through results
while($data=$sql->fetch_assoc()){
//Loop Thru the results adding to$myData
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$myData[] = "{c:[
{v: $count.0, f: 'One'},
{v: new Date($data[prep_date]), f: '$data[prep_date2]'}
]}";
}
}
}
return implode(',',$myData);
}
它不整洁,但可以为您工作为什么不使用json_encode()?我认为它将从数组中生成一个合适的json
在:
[]
是一个json数组
{}
是一个json对象
如果某些索引或值没有引号,则它不是json
,而是javascript对象
因此,您不能使用json\u encode
,必须手动输出对象的字符串表示形式
此外,您只是将数组值作为单个数组返回,但需要使用键作为索引将其拆分
foreach($row as $key => $value)
{
echo "$key: \'$value\'";
}
我还尝试了以下$json['rows']['c'][]=$row;“cols”部分看起来不错,谷歌不接受它?我认为行部分缺少一个{}分隔符。现在图表不接受我的数据。编辑:输入错误。我的意思是问题在于行部分。仔细看,原始海报需要一个json对象
而不是json
@hamidrezabstn您是对的,稍后在代码I encode de$json变量中。我编辑了代码以反映这一点。然而,我相信代码中的问题在于$json['rows']['c']=array_值($row);那么,我需要如何更改PHP代码以将json对象添加到“行”部分?现在它缺少了一组{}@Paul,如果您应该根据您提供的问题信息自行构建它,那么我认为这将有助于您:foreach($key=>row as$value){echo“{v:\'$value\'”;}