Basic looping with php to build json - php

I'm querying the instagram api to return json with this code:
$instagramClientID = '9110e8c268384cb79901a96e3a16f588';
$api = 'https://api.instagram.com/v1/tags/zipcar/media/recent?client_id='.$instagramClientID; //api request (edit this to reflect tags)
$response = get_curl($api); //change request path to pull different photos
So I want to decode the json
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
...
So now I want to reformat the contents of said array into a particular json format (geojson) the code would be roughly this:
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
)
And then use json_encode to return it all into a nice json file to cache on the server.
My question...is how to I use the code above to loop through the json? The outer structure of the array/json is static but the interior needs to change.

In this case it's better to build a new data structure instead of replacing the existing one inline.
Example:
<?php
$instagrams = json_decode($response)->data;
$features = array();
foreach ( $instagrams as $instagram ) {
if ( !$instagram->location ) {
// Images aren't required to have a location and this one doesn't have one
// Now what?
continue; // Skip?
}
$features[] = array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(
$instagram->location->longitude,
$instagram->location->latitude
),
'type' => 'Point'
),
'properties' => array(
'longitude' => $instagram->location->longitude,
'latitude' => $instagram->location->latitude,
// Don't know where title comes from
'title' => null,
'user' => $instagram->user->username,
// No idea where id comes from since instagram's id seems to belong in instagram_id
'id' => null,
'image' => $instagram->images->standard_resolution->url,
// Assuming description maps to caption
'description' => $instagram->caption ? $instagram->caption->text : null,
'instagram_id' => $instagram->id,
)
);
}
$results = array(
'type' => 'FeatureCollection',
'features' => $features,
);
print_r($results);

Related

Json array modification

I try to generate Donut chart code using Json array. I have stuck with in one place
This is my code
<?php
$canvas_data = array(
'type' => 'doughnut',
'data' => array(
'labels' => array(), // this array will be populated from the repeater
'datasets' => array(
'label' => '',
'backgroundColor' => array('#4e73df', '#1cc88a','#36b9cc','#df4e75'),
'borderColor'=> array('#ffffff','#ffffff','#ffffff','#ffffff'),
'data' => array() // this array will be populated from the repeater
)
),
'options' => array(
'maintainAspectRatio' => false,
'legend' => array(
'display' => false,
),
'title' => array()
),
);
// loop over repeater and populate object
if (have_rows('donut_graph_details')) {
while (have_rows('donut_graph_details')) {
the_row();
$canvas_data['data']['labels'][] = get_sub_field('title');
$canvas_data['data']['datasets']['data'][] = get_sub_field('percentage');
}
}
// use json encode to output attribute
?>
<canvas data-bs-chart='<?php echo json_encode($canvas_data); ?>'></canvas>
Out put using this code
<canvas data-bs-chart='{"type":"doughnut","data":{"labels":["IMPLEMENTED","PARTIALLY IMPLEMENTED","NOT IMPLEMENTED","UNDISCLOSED"],"datasets":{"label":"","backgroundColor":["#4e73df","#1cc88a","#36b9cc","#df4e75"],"borderColor":["#ffffff","#ffffff","#ffffff","#ffffff"],"data":["40","30","10","20"]}},"options":{"maintainAspectRatio":false,"legend":{"display":false},"title":[]}}'></canvas>
But I want to do small modification to the Out put. I want to add "[" before starting "datasets" and wants to close it . I have add the modification code below.
<canvas data-bs-chart='{"type":"doughnut","data":{"labels":["IMPLEMENTED","PARTIALLY IMPLEMENTED","NOT IMPLEMENTED","UNDISCLOSED"],"datasets":[{"label":"","backgroundColor":["#4e73df","#1cc88a","#36b9cc","#df4e75"],"borderColor":["#ffffff","#ffffff","#ffffff","#ffffff"],"data":["40","30","10","20"]}]},"options":{"maintainAspectRatio":false,"legend":{"display":false},"title":[]}}'></canvas>

place form data in multiples array and save in json format

I have a form with 3 pages and each page have different fields
in my controller i am able to make data in json format which is as
controller code
$input = $request->all();
unset($input['_token']);
unset($input['submit']);
$form_attributes = json_encode($input);
dd($form_attributes);
Output is as
"{"name":"test","student":"yes","email":"test.student#gmail.com","format":"auto",
"lists":["1,2"],"class_lists":["2,5"],"status":"1"}"
I not show full form so that it will easy to understand with small data
I want to make above out put as
its array should save as one main array Student then page1 array page2 array and then page3 array
it should be as
"Student":[{"arraypage1":[{"name":"test","student":"yes","email":"student#gmail.com"}],
"arraypage2":[{"format":"auto","lists":["1,2"]}],
"arraypage3":[{"class_lists":["2,5"],"status":"1"}]]"
Please help me to encode this data in above format
Thanks
You can easily build up an associative array in your desired format, then json_encode() it:
$formattedOutput = Array(
'student' => Array(
'arraypage1' => Array(
'name' => $input['name'],
'student' => $input['student'],
'email' => $input['email']
),
'arraypage2' => Array(
'format' => $input['format'],
'lists' => $input['lists']
),
'arraypage3' => Array(
'class_lists' => $input['class_lists'],
'status' => $input['status']
)
)
);
$form_attributes = json_encode($formattedOutput);
The exact key names may differ, but you should get the idea.
UPDATE:
To get the square brackets, you can wrap with additional Array():
$formattedOutput = Array(
'student' => Array(
Array('arraypage1' =>
Array(
Array(
'name' => $input['name'],
'student' => $input['student'],
'email' => $input['email']
)
)
),
Array('arraypage2' =>
Array(
Array(
'format' => $input['format'],
'lists' => $input['lists']
)
)
),
Array('arraypage3' =>
Array(
Array(
'class_lists' => $input['class_lists'],
'status' => $input['status']
)
)
)
)
);
see this post for more details: no square bracket json array

How to insert/retrieve images from a record in sugarcrm using REST API

How to insert and retrieve images from a record in suitecrm. I use the following procedure, but no images gets uploaded. I see no_image in the detail view.
$contents = file_get_contents('1436568236500.jpg');
$set_entry_list_parameters = array(
'session' => $login_result->id,
'module_name' => 'WBUR_Vehicle',
'name_value_list' => array(
array(
'name' => 'id',
'value' => '376e1f17-d797-b629-92cc-558f28228524'
),
array(
'name' => 'front_left_image_c',
'value' => base64_encode($contents)
)
)
);
$get_entry_list_result = call('set_entry', $set_entry_list_parameters, $url);
Also, how do I retrieve the images?

Generating data array from POST data with a param-map

I have the following two things:
$_POST array with posted data
$params array with a path for each param in the desired data array.
$_POST = array(
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
I would like to generate the $data array like the example below.
How can I do that?
Notice how the "paths" from the $params array are used to build the keys for the data array, filling it with the data from the $_POST array.
$data = array(
'User' => array(
'name' => 'Marcus',
),
'Page' => array(
'published' => 'Today',
'Data' => array(
'url' => 'http:://example.com',
'layout' => 'Some info...',
),
),
);
I would use referenced variables:
$post = array( // I renamed it
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
echo '<pre>'; // just for var_dump()
foreach($post as $key=>$var){ // take each $_POST variable
$param=$params[$key]; // take the scheme fields
$path=explode('.',$param); // take scheme fields as an array
$temp=array(); // temporary array to manipulate
$temp_original=&$temp; // we need this the same as we're going to "forget" temp
foreach($path as $pathvar){ // take each scheme fields
$temp=&$temp[$pathvar]; // go deeper
}
$temp=$var; // that was the last one, insert it
var_dump($temp_original); // analize carefully the output
}
All you have to do now is to combine them all, they are not exactly what you want, but this will be easy.
And please note, that each $temp_original fields are pointing at $post variable data! (&string instead of string). You may want to clone it somehow.

multiple JSON object response

I have a situation where i have a drop down in php file 'A'.and when i select a value from that drop down an ajax call is made and a different php file B is triggered.
In that file,i do db fetch,and form two json objects.these two json objects are required for me to draw 2 different data tables and 2 different charts.
when i echo one json object in 'B' i get that as a response to ajax call in 'A'
I cant even get a response if i echo two json objects in B.
for a single json object response,i can draw datatable and can manipulate json object with javascript and hopefully draw chart
Please advise how to handle this situation
Code from file B
$json = json_encode($tot_categ);
$json_percent = json_encode($tot_que_percent);
$cols_percent = array(
array( 'id' => 't', 'label' => 'Title', 'type' => 'string'),
array( 'id' => 'n', 'label' => 'Neutral(+) ', 'type' => 'string'),
array('id' => 'a', 'label' => 'Agree', 'type' => 'string'),
array('id' => 'ne', 'label' => 'Neutral(-)', 'type' => 'string'),
array('id' => 'd', 'label' => 'Disagree', 'type' => 'string'),
);
$jcols_percent = json_encode($cols_percent);
//JSON format accepted by Google tables
$r_percent= "{cols:".$jcols_percent.','."rows:".$json_percent."}";
//echo (JSON.stringify($r_percent));
// echo $r_percent;
$cols = array(
array( 'id' => 't', 'label' => 'Title', 'type' => 'string'),
array( 'id' => 'l', 'label' => 'Avg ', 'type' => 'string'),
array('id' => 'lb', 'label' => 'High', 'type' => 'string'),
array('id' => 'lo', 'label' => 'Low', 'type' => 'string')
);
$jcols = json_encode($cols);
//JSON format accepted by Google tables
$r = "{cols:".$jcols.','."rows:".$json."}";
//echo(json_decode($r));
echo $r;
$r and $r_percent are my objects
$r_percent when echoed gives
{cols:[{"id":"t","label":"Title","type":"string"},{"id":"n","label":"Neutral(+) ","type":"string"},{"id":"a","label":"Agree","type":"string"},{"id":"ne","label":"Neutral(-)","type":"string"},{"id":"d","label":"Disagree","type":"string"}],rows:[{"c":[{"v":"165q"},{"v":0},{"v":0},{"v":0},{"v":100}]},{"c":[{"v":"160q"},{"v":0},{"v":0},{"v":0},{"v":6}]},{"c":[{"v":"161q"},{"v":0},{"v":0},{"v":0},{"v":10}]},{"c":[{"v":"162q"},{"v":7},{"v":0},{"v":7},{"v":0}]},{"c":[{"v":"163q"},{"v":0},{"v":25},{"v":0},{"v":0}]},{"c":[{"v":"164q"},{"v":0},{"v":100},{"v":0},{"v":0}]}]}
$r when echoed gives
{cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"165q"},{"v":1.3333333333333},{"v":"2"},{"v":"1"}]},{"c":[{"v":"160q"},{"v":6},{"v":"10"},{"v":"1"}]},{"c":[{"v":"161q"},{"v":6.6666666666667},{"v":"9"},{"v":"2"}]},{"c":[{"v":"162q"},{"v":7},{"v":"9"},{"v":"3"}]},{"c":[{"v":"163q"},{"v":8},{"v":"9"},{"v":"6"}]},{"c":[{"v":"164q"},{"v":5},{"v":"5"},{"v":"5"}]}]}
when combined
$result = array('objA' => $r_percent, 'objB' => $r );
echo json_encode($result);
updated echoing
{"objA":"{cols:[{\"id\":\"t\",\"label\":\"Title\",\"type\":\"string\"},{\"id\":\"n\",\"label\":\"Neutral(+) \",\"type\":\"string\"},{\"id\":\"a\",\"label\":\"Agree\",\"type\":\"string\"},{\"id\":\"ne\",\"label\":\"Neutral(-)\",\"type\":\"string\"},{\"id\":\"d\",\"label\":\"Disagree\",\"type\":\"string\"}],rows:[{\"c\":[{\"v\":\"165q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":100}]},{\"c\":[{\"v\":\"160q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":6}]},{\"c\":[{\"v\":\"161q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":10}]},{\"c\":[{\"v\":\"162q\"},{\"v\":7},{\"v\":0},{\"v\":7},{\"v\":0}]},{\"c\":[{\"v\":\"163q\"},{\"v\":0},{\"v\":25},{\"v\":0},{\"v\":0}]},{\"c\":[{\"v\":\"164q\"},{\"v\":0},{\"v\":100},{\"v\":0},{\"v\":0}]}]}","objB":"{cols:[{\"id\":\"t\",\"label\":\"Title\",\"type\":\"string\"},{\"id\":\"l\",\"label\":\"Avg \",\"type\":\"string\"},{\"id\":\"lb\",\"label\":\"High\",\"type\":\"string\"},{\"id\":\"lo\",\"label\":\"Low\",\"type\":\"string\"}],rows:[{\"c\":[{\"v\":\"165q\"},{\"v\":1.3333333333333},{\"v\":\"2\"},{\"v\":\"1\"}]},{\"c\":[{\"v\":\"160q\"},{\"v\":6},{\"v\":\"10\"},{\"v\":\"1\"}]},{\"c\":[{\"v\":\"161q\"},{\"v\":6.6666666666667},{\"v\":\"9\"},{\"v\":\"2\"}]},{\"c\":[{\"v\":\"162q\"},{\"v\":7},{\"v\":\"9\"},{\"v\":\"3\"}]},{\"c\":[{\"v\":\"163q\"},{\"v\":8},{\"v\":\"9\"},{\"v\":\"6\"}]},{\"c\":[{\"v\":\"164q\"},{\"v\":5},{\"v\":\"5\"},{\"v\":\"5\"}]}]}"}
Combine both responses in a single object, return that object and use both parts separately again:
PHP side:
$result = array( 'objA' => $objA, 'objB' => $objB );
echo json_encode( $result );
Client side:
// your success callback handler
function handler( data ) {
// execute code for object A
doStuff( data.objA );
// execute code for object B
doOtherStuff( data.objB );
}

Categories