[英]Generate JSON for Google Charts using PHP
I'm following the guide at: https://developers.google.com/chart/interactive/docs/php_example 我在以下位置遵循该指南: https : //developers.google.com/chart/interactive/docs/php_example
They give a json snippet for a json example. 他们给出了一个json示例的json片段。 How do yo build this one with php? 如何用php构建这个? Usually there is just converting arrays to json using json_encode() but this time it seems like you need an object aswell. 通常只有使用json_encode()将数组转换为json,但这一次似乎还需要一个对象。 Can anyone clarify this? 谁能澄清一下?
The json snippet: JSON代码段:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
What I have so far: 到目前为止,我有:
$obj = new stdClass();
$obj->cols= array(
array("id"=>"", "label"=>"Topping", "pattern"=>"", "type"=>"string"),
array("id"=>"", "label"=>"Slices", "pattern"=>"", "type"=>"string"));
$obj->rows = array(
array()
);
echo json_encode($obj);
Is there anyone that knows how to complete this php representation? 有没有人知道如何完成此php表示形式?
Edit: My echo outputs: 编辑:我的回声输出:
{"cols":[{"id":"","label":"Topping","pattern":"","type":"string"},{"id":"","label":"Slices","pattern":"","type":"string"}],"rows":[[]]}
PHP associative arrays will converts to objects in JSON, so stdClass
is not needed. PHP关联数组将转换为JSON中的对象,因此不需要stdClass
。 You already got 80% of the structure so here are a few pointers: 您已经拥有80%的结构,因此这里有一些提示:
$data = [
'cols' => [],
'rows' => [],
];
will result in : 将导致:
{
'cols': [],
'rows': [],
}
In order to get JSON arrays, don't give keys to the values: 为了获取JSON数组,请不要给这些值指定键:
$data = [
'c' => [
[ // <- no key here
'v' => 'Mushroom',
'f' => null
],
[ // <- no key here
'v' => '3',
'f' => null
],
],
// ...
];
will give you a data row: 会给你一个数据行:
{
"c": [ // <- we got an actual array here because there was no key
{
"v":"Mushrooms",
"f":null
},
{
"v":3,
"f":null
}
]
}
This code should work: 此代码应工作:
<?php
$obj = array("cols"=>array(
array("id"=>"", "label"=>"Topping", "pattern"=>"", "type"=>"string"),
array("id"=>"", "label"=>"Slices", "pattern"=>"", "type"=>"string")),
"rows"=>array(
array("c"=>array(array("v"=>"Mushrooms", "f"=>null), array("v"=>3, "f"=>null))),
array("c"=>array(array("v"=>"Onions", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Olives", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Zucchini", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Pepperoni", "f"=>null), array("v"=>2, "f"=>null))),
)
);
echo json_encode($obj);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.