Generate JSON for Google Charts using PHP - 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":[[]]}

PHP associative arrays will converts to objects in JSON, so stdClass is not needed. You already got 80% of the structure so here are a few pointers:
$data = [
'cols' => [],
'rows' => [],
];
will result in :
{
'cols': [],
'rows': [],
}
In order to get JSON arrays, don't give keys to the values:
$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);
?>

Related

Why does flattening a collection of collections yield into an array of all the arrays values?

Using laravel, I create a collection of collection of array items.
I expect to work on each array item during the map by first flattening the collection of collections.
Yet instead of getting each array item, I suddenly iterate over each array's value (the key ist lost in the process). Why? What is going on here?
public function testItFlattensCollectionOfCollections()
{
$json = <<<JSON
[
[
{
"userId": "10",
"foo": "bar"
},
{
"userId": "11",
"foo": "baz"
}
],
[
{
"userId": "42",
"foo": "barbaz"
}
]
]
JSON;
$content = json_decode($json, true);
$collection = collect($content)
->map(fn ($items) => collect($items))
->flatten();
$actual = $collection->toArray();
$this->assertSame(
[
[
'userId' => '10',
'foo' => 'bar',
],
[
'userId' => '11',
'foo' => 'baz',
],
[
'userId' => '42',
'foo' => 'barbaz',
],
],
$actual
);
$this->assertNotSame(['10', 'bar', '11', 'baz', '42', 'barbaz'], $actual);
}
$collection = collect($content)
->map(fn ($items) => collect($items))
->flatten(depth: 1)
If you take a look at the collection's flatten method, you will see it offers an optional parameter $depth and it defaults to infinity.
It therefore tries to flat it down as far as possible, which in your case basically means it flattens twice, both your collection of collections and also all the arrays within each collection.

Generate php array definition from JSON

My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.

Convert PHP to JSON with Nested Array

I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);

Create JSON in PHP with multiple levels

I need to create json with multiple levels via PHP.
{
"accident": {
"dateTime": "2015-08-08T16:12:08",
"desc": "string"
},
"calculationInput": {
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
"wageRates": {
"labourRate1": 10,
"labourRate2": 11,
"labourRate3": 22,
"labourRate4": 33,
"labourRateD": 44,
"paintRate": 55
}
},
"caseNumber": "F4Q",
"vehicle": {
"adminData": {
"firstRegDate": "2015-07-08",
"numberPlate": "MI214AF"
},
"identification": {
"vin": "VF7S6NFZF56215577"
},
"owner": {
"city": "Praha",
"country": "CZE",
"email": "mail#mail.com",
"name": "Fero Taraba",
"phone": "777111222",
"phone2": "999555333",
"postCode": "07101",
"street": "Kukureliho 18"
}
}
}
I actuyltry this and it's possible for me to create single level json, with other words:
$data = array (
"caseNumber" =>"F4Q"
);
and then just easy:
$data_json= json_encode($data);
But can someone explain me how can I do this second or even 3th level tree to convert to JSON?
I will really appriciate your help guys. Thanks
EDIT:
Most of the answers really lead me right way, only problem now is this part:
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
where there is [ ] which represent some list of blockCodes. Any idea what to do with this ? :)
What is your question exactly?
You can create a array and then just encoding it to json?
$data = array(
'Key 1' => array(
'Key 2 - Key 1' => array(
'Key 3 - Key 1' => array()
)
)
);
echo json_encode($data);
Just use associative arrays
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
print out
{"caseNumber":"F4Q","vehicle":{"adminData":{"firstRegDate":"2015-07-08","numberPlate":"MI214AF"},"identification":{"vin":"VF7S6NFZF56215577"}}}
Use associative Arrays:
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
echo json_encode($data)
you get your brackets by putting an additional array around your object.
$data = array("idBlockCodes" => array(
array(
"code" => 51,
"value" => 1
)
)
);
print json_encode($data);
For you to convert all of your data to array:
You must first use json_encode();
$a = json_encode($yourData);
And then decode it:
$b = json_decode($a, true);
echo '<pre>';
print_r($b); //print it
It displays associated arrays with it

JSON encode multiplies arrays as single array

$array = array(
$this->_order->revenue_seller($value,$from,$to),
$this->_order->refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this->_order->sales_seller($value,$from,$to)
);
$this->response($array,200);
I want the data to be be displayed as a single array, but as we can see, the output is begin displayed as array of arrays:
[
[
{
"min_amount":"2.00",
"max_amount":"2.00",
"avg_amount":"2.000000",
"total_revenue":"2.00"
}
],
[
{
"total_refund_amount":"1.00"
}
],
[
{
"created_at":"2013-03-24 15:04:35"
}
],
[
{
"quantity":"1"
}
]
]
How can I make the data appear as one single array?
Like this:
[
{
"day":"2013-03-19",
"min_amount":"0.00",
"max_amount":"0.00",
"avg_amount":"0.000000",
"total_revenue":"0.00",
"quantity" : "1",
"total_refunded_amount":null,
"created_at":"2013-03-24 15:04:35"
}]
If you are getting array return by all four function than use array_merge as,
$array = array_merge($this->_order->revenue_seller($value,$from,$to),
$this->_order-refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this-_order->sales_seller($value,$from,$to));
$this->response($array,200);
DEMO.

Categories