I am stumped on producing a specifically formatted JSON for a flot chart. Any help is much appreciated!
I use this php code
$query = mysql_query('SELECT * FROM all_programs_extended');
while($row = mysql_fetch_assoc($query)) {
$newData[] = array(
'label' => $row['program_type'],
'data' => array(
"employee1" => $row['employee1'],
"employee2" => $row['employee2'],
"employee3" => $row['employee3']
)
);
}
print json_encode($newData);
which produces this valid JSON
[{"label":"Program A","data":{"employee1":"5","employee2":"3","employee3":"1"}},
{"label":"Program B","data":{"employee1":"0","employee2":"4","employee3":"2"}},
{"label":"Program A","data":{"employee1":"4","employee2":"2","employee3":"4"}}]
but I need it look like this:
{
"label": "Program A",
"data": [[employee1, 5], [employee2, 3], [employee3, 1]],
"label": "Program B",
"data": [[employee1, 0], [employee2, 4], [employee3, 2]],
"label": "Program C",
"data": [[employee1, 4], [employee2, 2], [employee3, 4]]
}
I seem to have mixed up by brackets and braces, and I also need a comma separating my value pairs between brackets rather than the colon in the first JSON. Be nice to get ride of the quotation marks around the numbers too!
Thanks very much!
Just suround employeeX by an additional array:
$newData[] = array(
'label' => $row['program_type'],
'data' => array(
array(
"employee1" => $row['employee1']
),
array (
"employee2" => $row['employee2']
),
array (
"employee3" => $row['employee3']
)
)
);
Related
i done search tutorial for send post json with curl ..
but for this value i cant find in here..
and my question how to convert to array post json in value if like
this, and this my value post json
{
"payment_type": "bca_klikpay",
"transaction_details": {
"order_id": "orderid-01",
"gross_amount": 11000
},
"item_details": [
{
"id": "1",
"price": 11000,
"quantity": 1,
"name": "Mobil "
}
],
"customer_details":{
"first_name": "John",
"last_name": "Baker",
"email": "john.baker#email.com",
"phone": "08123456789"
},
"bca_klikpay": {
"description": "Pembelian Barang"
}
}
i done try to php array like this but still error
$item = array('id' => 'id1', 'price' => 11000, 'quantity' => 1 , 'name' => 'Mobil');
$data2 =array('payment_type' => 'bca_klikpay',
'transaction_details' => array('order_id' => 'orderid-01', 'gross_amount' => 11000),
'item_details' => array([$item]),
'customer_details'=> array('first_name' => 'john',
'last_name' => 'baker', 'email' => 'john.baker#email.com', 'phone' => 08123456789),
'bca_klikpay' => array('description' => 'Pembelian Barang'));
maybe someone can help me.. and sory for my bad english
thanks
There is the following error - the phone number has to be string, not number, so it would look like this 'phone' => '08123456789', because numbers cannot begin with 0.
Beside this, there is the following issue - You should not set item_details like this, but rather 'item_details' => [$item]. You do not need 2 nested arrays, just one. (array() is equal to []. They are practically the same in your use case. So you are doing something like array(array($item)), which is wrong)
What else, you have to do a $json = json_encode($data2); at the end and it will return what you want it to.
So I found an answer which is supposed to work, however it doesn't appear too...
Already accepted answer with the same issue.
I have got the following array called $banners:
[
0 => [
"bannerCustomTemplate" => 0,
"bannerId" => 1,
"bannerType" => 1,
"bannerTitle" => "Merry",
"bannerStrapline" => "Christmas",
"bannerPeriod" => "2018-12-01 to 2018-12-10",
"bannerText" => "Christmas opening hours"
],
1 => [
"bannerCustomTemplate" => 0,
"bannerId" => 7,
"bannerType" => 2,
"bannerTitle" => "Easter",
"bannerStrapline" => "Test",
"bannerPeriod" => "2018-12-04 to 2018-12-12",
"bannerText" => "dsadasdaas"
]
]
The answers I have read suggest $all_banners = call_user_func_array('array_merge', $banners);.
However this is giving me:
[
"bannerCustomTemplate" => 0,
"bannerId" => 7,
"bannerType" => 2,
"bannerTitle" => "Easter",
"bannerStrapline" => "Test",
"bannerPeriod" => "2018-12-04 to 2018-12-12",
"bannerText" => "dsadasdaas"
]
Seems like it's just replacing rather than merging. Anyone got any ideas?
Edit
Just read the following comment
Little note here. The updated variant with unpacking array doesn't work with string keys. But the first one works perfect. Just keep in mind this. – Alliswell
So I have now updated my code with another solutions, with the same results.
Edit 2
Well, merging is merging not replacing. So what I expect is:
[
"bannerCustomTemplate" => [ 0, 0 ],
"bannerId" => [ 1, 7 ],
"bannerType" => [ 1, 2 ],
"bannerTitle" => [ "Merry", "Easter" ]
"bannerStrapline" => [ "Christmas", "Test" ]
"bannerPeriod" => [ "2018-12-01 to 2018-12-10", "2018-12-04 to 2018-12-12" ]
"bannerText" => ["Christmas opening hours", "dsadasdaas" ]
]
If all your arrays are known to contain the same keys in the same order, this is probably easiest:
$data = [
['foo' => 'bar', 'baz' => 42],
['foo' => 'baz', 'baz' => 69]
];
$result = array_combine(array_keys($data[0]), array_map(null, ...$data));
This uses the useful behaviour of array_map with null as the callback to take one element from each input array and return a new combined array.
I have this array:
$arr = array(
'reportDescription' => array(
'reportSuiteID' => 'globretailprod',
'elements' => array(
0 => array(
'id' => $queryElement
)
),
'metrics' => array(
0 => array(
'id' => $queryMetric
)
)
)
);
I'm trying to insert some code into the array using an if command. This is what I have:
if (isset($querySegment)) {
$arr['reportDescription']['segments'] = $querySegment;
}
However that gives me the wrong result, what I am trying to achieve is this:
{
"reportDescription": {
"reportSuiteID": "rbsglobretailprod",
"dateFrom": "2018-09-09",
"dateTo": "2018-09-10",
"dateGranularity": "day",
"metrics": [{
"id": "pageviews"
}],
"elements": [{
"id": "page"
}],
"segments": [{
"id": "jjj"
}]
}
}
Notice there are two issues with this. Firstly, segments isn't isn't insert with an id, it's just inserted as a value. Secondly, I am a bit concerned about the trailing comma after metrics in my original array, since I need to be able to add a comma after the metrics array if I do include segments.
Just use the same format as you use for the other items to get the same structure...
if (isset($querySegment)) {
$arr['reportDescription']['segments'] = array(
0 => array(
'id' => $querySegment
)
);
}
As for the comma, this should be added automatically as needed if your using json_encode()
I'm using an API which gives an example of how they want the data of the POST request I'm about to make to be formatted. This is their example:
un=chris&
key=xxxx&
origin=plot&
platform=lisp&
args=[[0, 1, 2], [3, 4, 5], [1, 2, 3], [6, 6, 5]]&
kwargs={"filename": "plot from api",
"fileopt": "overwrite",
"style": {
"type": "bar"
},
"traces": [1],
"layout": {
"title": "experimental data"
},
"world_readable": true
}
I'm confused about how I should put together this data from existing arrays in PHP. From what I understand the example show an encoded "string" that is just partly encoded? As of now I am putting the string together all by myself through extracting the keys and values from the arrays.
I'm looking for a more neat way of doing this with existing methods?
I believe using http_build_query will solve this for you.
Given the example, here's sample of how to use it:
$args = array(array(0,1,2), array(3,4,5), array(1,2,3), array(6,6,5));
$kwargs = array(
'filename' => 'plot from api',
'fileopt' => 'overwrite'
'style' => array('type' => 'bar'),
'traces' => array(1),
'layout' => array('title' => 'experimental data'),
'word_readable' => true
);
$request = array(
'un' => 'chris',
'key' => 'xxx',
'origin' => 'plot',
'platform' => 'lisp',
'args' => $args,
'kwargs' => $kwargs
);
$queryString = http_build_query($request);
echo $queryString;
More info: https://php.net/http_build_query
So my code here:
$featurecollection = ("FeatureCollection");
$test[] = array (
"type" => $featurecollection,
$features[] = array($images)
);
file_put_contents($cache,json_encode($test));
results in the following json:
[
{
"type":"feature",
"0":[
[
{
"title":"some title",
"src":"value",
"lat":"value",
"lon":"value"
},
{
"title":"some title",
...
But I need to nest things differently and I'm perplexed on how the php array should be constructed in order to get a result like:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":{
"coordinates":[
-94.34885,
39.35757
],
"type":"Point"
},
"properties":{
"latitude":39.35757,
"title":"Kearney",
"id":919,
"description":"I REALLY need new #converse, lol. I've had these for three years. So #destroyed ! :( Oh well. Can't wait to get a new pair and put my #rainbow laces through. #gay #gaypride #bi #proud #pride #colors #shoes #allstar #supporting ",
"longitude":-94.34885,
"user":"trena1echo5",
"image":"http://images.instagram.com/media/2011/09/09/ddeb9bb508c94f2b8ff848a2d2cd3ece_7.jpg",
"instagram_id":211443415
}
},
What would the php array look like for that? I'm thrown off by the way everything is nested but still has a key value.
Here's how I'd represent that in PHP:
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
So to get that structure, each feature has to be an associative array of:
type,
geometry - an associative array of:
coordinates - an indexed array of values,
type
properties - an associative array of values like latitude, longitude, id etc.
It's times like these when I prefer languages that distinguish between lists (array(1, 2, 3)) and dictionaries or maps (array('a' => 1, 'b' => 2)).
With PHP 5.4 and above:
$array = [
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'geometry' => [
'coordinates' => [-94.34885, 39.35757],
'type' => 'Point'
], // geometry
'properties' => [
// latitude, longitude, id etc.
] // properties
], // end of first feature
[] // another feature, and so on
] // end of features
];
For the PHP script below:
<?php
header('Content-type=> application/json');
echo json_encode($array);
This is the JSON output;
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"coordinates": [
-94.34885,
39.35757
],
"type": "Point"
},
"properties": []
},
[]
]
}