DaveLar DaveLar - 4 months ago 25
PHP Question

Generate JSON for Google Charts using PHP

I'm following the guide at:
https://developers.google.com/chart/interactive/docs/php_example

They give a json snippet for a json example. How do yo build this one with php? Usually there is just converting arrays to json using json_encode() but this time it seems like you need an object aswell. Can anyone clarify this?

The json snippet:

{
"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?

Edit:
My echo outputs:

{"cols":[{"id":"","label":"Topping","pattern":"","type":"string"},{"id":"","label":"Slices","pattern":"","type":"string"}],"rows":[[]]}

Answer

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);
?>
Comments