creating json output using php - php

I have this so far :
if (is_request_var('requestor') == 'PPA'){
$dataJson[][] = array("status" => "success","value" => $fetchValue ,"postcode" => $fetchPostCode,"params"=>"");
$notice = $dataJson;
}
I want to get (refer below) from PHP how do i arrange my PHP array code
jQuery191013316784294951245_1485527378760([
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e KENYATTA AVENUE, GENERAL POST OFFICE, 00100",
"postcode": "00100"
},
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e HAILE SALASSIE AVENUE, CITY SQUARE, QLD, 00200",
"postcode": "00200"
}
])

Try this:
$dataJson = array("value" => $fetchValue, "postcode" => $fetchPostCode);
$notice = json_encode($dataJson);
echo $notice;
Returns a string containing the JSON representation of value.
http://php.net/manual/en/function.json-encode.php

Related

Need help parsing JSON output

I'm making a REST call in PHP and returning JSON. I'm eventually putting this into tables, but trying to output the value for now to get the hang of it.
There are values in the "data" field I would like to get into variables. In my example they would be "201807", 23.43 and "201806", 22.54. It's the first two values of the property "data"
My code looks like this:
<?php
$service_url = "http://api.eia.gov/geoset/?geoset_id=ELEC.PRICE.RES.M&regions=USA-AL,USA-AK,USA-AR&api_key=3a8b92cfaf3a21e2e990f228c9152eeb&out=json&start=2018";
$get_data = callAPI('GET', $service_url, false);
$response = json_decode($get_data);
foreach ($response as $r) {
echo $row->name;
echo $row->geoset_id;
}
?>
And JSON looks like this:
{
"geoset": {
"geoset_id": "ELEC.PRICE.RES.M",
"setname": "Average retail price of electricity : residential : monthly",
"f": "M",
"units": "cents per kilowatthour",
"unitsshort": null,
"series": {
"USA-AK": {
"series_id": "ELEC.PRICE.AK-RES.M",
"name": "Average retail price of electricity : Alaska : residential : monthly",
"region": "USA-AK",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 23.43],
["201806", 22.54],
["201805", 22.16],
["201804", 21.61],
["201803", 21.47],
["201802", 21.11],
["201801", 21.67]
]
},
"USA-AL": {
"series_id": "ELEC.PRICE.AL-RES.M",
"name": "Average retail price of electricity : Alabama : residential : monthly",
"region": "USA-AL",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 12.28],
["201806", 12.41],
["201805", 12.49],
["201804", 12.79],
["201803", 12.65],
["201802", 12.29],
["201801", 11.59]
]
},
"USA-AR": {
"series_id": "ELEC.PRICE.AR-RES.M",
"name": "Average retail price of electricity : Arkansas : residential : monthly",
"region": "USA-AR",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 9.98],
["201806", 9.99],
["201805", 9.89],
["201804", 10],
["201803", 10.47],
["201802", 9.8],
["201801", 9.36]
]
}
}
}
}
So far I'm getting NULL values back.
As you have used json_decode your result will be convert to object type. so you should do as follows:
$geoset = $response->geoset;
$geosetid = $geoset->geoset_id;
foreach ($geoset->series as $row) {
echo $row->name;
$data = $row->data; //this will produce the values as array
}
Your data array will be like this:
Array
(
[0] => Array
(
[0] => 201807
[1] => 23.43
)
[1] => Array
(
[0] => 201806
[1] => 22.54
)
)
...
Hopefully this helps! :)
Your code will never work, because:
You iterate $response as $r, but use $row inside;
The $response has only one child: geoset. There is no $response->name neither $response->geoset_id.
If you want the geoset_id, you must access using: $response->geoset->geoset_id.
To achieve this:
There are values in the "data" field I would like to get into variables
Use the following code:
foreach ($response->geoset->series as $series) {
foreach ($series->data as $data) {
$date = $data[0];
$value = $data[1];
}
}

slack, php and json - Valid Markup for iterating app selections

I've been trying to create a slack app which takes the basic information of the name and sku of the product and places it within a select box that appears in slack. Unfortunately my code to populate the valid json is going wrong somewhere when i try to itterate using a loop.
Valid Json is here:
{
"text": "Great! You want to find something!",
"attachments": [
{
"text": "Please type what you want to find",
"fallback": "Sorry! Cant do that at the moment!",
"callback_id": "cg_selectproduct",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "cg_choice",
"text": "Find Product",
"type": "select",
"options": [
{
"text": "option1",
"value": "option1"
},
{
"text": "option2",
"value": "option2"
},
{
"text": "option3",
"value": "option3"
}]
}
]
}
]
}
This works perfectly fine without the iteration. I have no issues if i tell the app to go here. It displays all options correctly.
Invalid PHP
$check = ($dbh->prepare("SELECT * FROM product_list WHERE FAMILY='PARENT'"));
$check->execute();
$row = $check->fetchAll();
// execute a pdo search to find all product parents
$jsonInput = "";
foreach($row as $rows){
$jsonInput .= '"text"=>"' . $rows['PRODUCT_NAME'] . '", "value" => "' . $rows['SKU'] . '",';
}
$jsonInput = rtrim($jsonInput, ',');
//Create an iterative string which will contain the product names and skus, removing the comma at the end.
header('Content-Type: application/json');
//Set the content type to json
$optionSelect = array(
"text" => "Great! You want to find something!",
"attachments" =>array(
"text" => "Please type what you want to find",
"fallback" => "Sorry! Cant do that at the moment!",
"callback_id" => "cg_selectproduct",
"color"=> "#3AA3E3",
"attachment_type" => "default",
"actions" => array(
"name" => "cg_choice",
"text" => "Find Product",
"type" => "select",
"options" => array($jsonInput)
)
)
);
//Create and itterate the options for the selection so it's populated
print_r(json_encode($optionSelect));
//print to show json
I'm not 100% sure where i'm going wrong with this. Maybe i'm thinking about a minor part a little too much. Can anyone here help me with where i'm going wrong?
$jsonInput = [];
foreach($row as $rows) {
$jsonInput[] = array(
'text' => $rows['PRODUCT_NAME'],
'value' => $rows['SKU']
);
}
// ...........
"options" => $jsonInput

How to get data from JSON file by parsing array name from the url

I am trying to print data in json format from my 'data.json' file. With my php file (alldata.php), I could get all data (arrays) pretty printed. But where I want you to help me is how to get a specific array name and it objects/content.
My alldata.php looks like this:
{
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
"nationality": "Spain",
"marketValue": "9,000,000 €",
"created": "2017-04-15 10:04:58"
}],
"articles": [
{
"author": "Stephen Walter",
"title": "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url": "http://www.telegraph.co.uk/news/2017/04/15/disruptive-stag-party-revellers-thrown-plane-manchester-airport/",
"publishedAt": "2017-04-15T09:25:10Z"
}],
land": [
{
"state": "Somewhr",
"found": "1889",
"area": "6,812",
"empl": "1,325",
"ppl": "16,842"
}]
}
In php, how can I get an array e.g "players" with the content by using url such as 'alldata.php?search=players'
Here is a code sample....
//get content of the JSON API using file_get_contents()
$url = ('myJson.json');
$jsondata = file_get_contents($url);
//convert json object to php associative array
$data = json_decode($jsondata, true);
what do I do here to query the data.json file for a specific array?????
header('Content-Type: application/json; charset=UTF-8');
$json_string = json_encode($????????????, JSON_PRETTY_PRINT);
print $json_string;
Thanks
If I properly understood what you mean, and if your array has always the same tree, this wilp help you access the data :
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$array = array(
0 => array(
"players" => array(
"name" => "Marcos Alonso",
"position" => "Left-Back",
"nationality" => "Spain",
"marketValue" => "9,000,000 €",
"created" => "2017-04-15 10:04:58"
),
"articles" => array(
"author" => "Stephen Walter",
"title" => "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url" => "http://www.telegraph.co.uk/news/2017/04/15/",
"publishedAt" => "2017-04-15T09:25:10Z"
),
"land" => array(
"state" => "Somewhr",
"found" => "1889",
"area" => "6,812",
"empl" => "1,325",
"ppl" => "16,842"
)
),
1 => array(
"players" => array(
"name" => "Sebastian Vettel",
"position" => "Driver",
"nationality" => "Germany",
"marketValue" => "9,000,000 €",
"created" => "2013-03-15 11:04:52"
),
"articles" => array(
"author" => "Stephen Walter",
"title" => "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url" => "http://www.telegraph.co.uk/news/2017/04/15/",
"publishedAt" => "2017-04-15T09:25:10Z"
),
"land" => array(
"state" => "Somewhr",
"found" => "1889",
"area" => "6,812",
"empl" => "1,325",
"ppl" => "16,842"
)
)
);
/* end of array */
$data1 = json_encode($array); /* just checking - not needed after that */
$data = json_decode($data1, true); /* just checking - not needed after that */
$needle = "articles"; /* should be $needle = $_GET['search']; and checked before use */
//print_r($data); /* just checking */
foreach($data as $value){ /* we access 1st level */
echo '** Needle is: '.$needle.' **<br/>';
foreach($value[$needle] as $sub_key => $sub_data){ /* we access 2nd level */
echo $sub_key.'-->'.$sub_data.'<br/>'; }
}
?>
Once you access the data, you can easily do what you want with it...

Build new custom Array from Wordpress $wpdb->get_results array

I'm currently taking the results of a table and using wp_send_json to using it as a JSON response. The data is encoded as expected, however I'd like to tweak the output a bit by changing the keys, formating, and order. I'm not sure how to rebuild the array and encode as json after so I'm looking for a little bit of help.
$stuff= $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_table"), ARRAY_A);
wp_send_json($stuff);
As of now the results I get via print_r look as follows.
Array(
[0] => Array(
[id] => 1[gender] => Male[email] => test#loas . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
) [1] => Array(
[id] => 2[gender] => Female[email] => femal#test . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
)
)
When encoded I get:
[{
"id": "1",
"gender": "Male",
"email": "test#loas.com",
"lat": "45",
"long": "-76",
"country_srt": "USA",
"country_long": "United States"
}, {
"id": "2",
"gender": "Female",
"email": "femal#test.com",
"lat": "98",
"long": "-34",
"country_srt": "USA",
"country_long": "United States"
}]
Thing is, I don't really need some of these values and also need to format some things to output for easy map plotting. For instance the country longform and gender go into an html formatted string. What I'm looking to do is transform this array to result in:
[ idhere: {
"value": "1",
"latitude": "45",
"longitude": "-76",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}, idhere: {
"value": "2",
"latitude": "98",
"longitude": "-34",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}]
I think what you need to do is break down the process down into steps (so you can change the data around) instead of sending your sql data to json directly.
build your own array
iterate over your sql result set while adding your own markup
send the output to json
something like:
$preJSON = array();
// select only columns you need
$sql = "SELECT id, gender, country_srt, lat, long
FROM wp_table"
$count = 0; // this is for $preJSON[] index
foreach( $wpdb->get_results( $sql ) as $key => $row ) {
// each column in your row will now be accessible like this:
// $my_column = $row->column_name;
// now we can do:
$value = $row->id;
$latitude = $row->lat;
$longitude = $row->long;
$gender = $row->gender;
$country = $row->country_srt;
$tooltip = array(
"content" => "HTML and stuff" . $gender . "more HTML and stuff" . $country
);
// now we can build a row of this information in our master array
$preJSON[$count] = array(
"value" => $value,
"latitude" => $latitude,
"longitude" => $longitude,
"tooltip" => $tooltip
);
// increment the index
++$count;
}
// after foreach
// send the whole array to json
$json = json_encode( $preJSON );
I believe this should be the basic gist of what you need

How do I remove nested object from an object in CakePHP?

CakePHP API returns result like this:
{
"status": "OK",
"themes": [
{
"Theme": {
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
}
]
}
I would like to ask, how can in remove nested Theme object to get result like this?:
{
"status": "OK",
"themes": [
{
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
]
}
Here is my CakePHP code:
$this->Theme->recursive = -1;
// GET USER ID
$themeData['user_id'] = $isSessionValid;
// GET ALL THEMES RELATED TO USER
$foundThemes = $this->Theme->find('all', array(
'conditions' => array(
'Theme.user_id' => $themeData['user_id'])
)
);
$themes = array();
// FOREACH THEMES AND GET COUNT FOR CARDS FOR EACH THEME
foreach($foundThemes as $foundTheme) {
// GET COUNT OF QUESTIONS FOR ACTUAL THEME
$countOfCards = $this->Theme->Card->find('count', array(
'conditions' => array(
'Card.theme_id' => $foundTheme['Theme']['id'])
)
);
// APPEND TO ACTUAL ARRAY
$foundTheme['Theme']['count_of_cards'] = $countOfCards;
array_push($themes,$foundTheme);
}
// SET SUCCESS RESPOSNSE
$this->set(array(
'status' => 'OK',
'themes' => $themes,
'_serialize' => array(
'status',
'themes',
)
));
Many thanks for any advice.
You can manipulate CakePHP's array formats using its built in Hash utility: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash
What I would do would be to flatten the results:
$results = Hash::flatten($results);
Your data array will end up as a single dimensional array looking like this:
$results = array(
'status' => 'OK'
'themes.0.Theme.id' => 20,
...
'themes.1.Theme.id' => 21,
...
);
You can then use string replace to remove "Theme" from your keys:
$keys = array_keys($results);
$keys = str_replace('Theme.', '', $keys);
Then you can use Hash::expand to get your original array, now formatted how you want:
$results = Hash::expand(array_combine($keys, array_values($results)));
I dont think CakePHP supports this. if you want to do this with an easy way check the Set Utility.
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html

Categories