How to get the JSON data from the Groupon API - json

I am struggling to get the "merchant" -> "id" from the Groupon API below, while I don't have any problems to return the discountPercent.
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $results) {
$discountPercent = $results['options'][0]['discountPercent'];
$merchantId = $results['merchant'][0]->id;
echo $discountPercent.'<br>';
echo $merchantId;
}
?>
If someone could point me to the right direction.
Many Thanks,

Ok here is the answer:
$merchantId = $results['merchant']['id'];

>>>This may be the Reason.....
>>>Explanation for:: $results['options'][0]['discountPercent']
In $json array you can see
[options] => Array
(
[0] => Array
(
.........
[discountPercent] => 54
.........
)
)
Here, the hierechy is
option->0(key)->discountPercent
that's why you need to use index '0';
>>>Explanation for::: $results['merchant'][0]->id
in json array you can see
[merchant] => Array
(
[id] => global-cuisine-restaurant
[uuid] => 183dd76b-a1a6-40cf-93c7-33e00f379451
[name] => Global Cuisine Restaurant
[websiteUrl] => http://www.globalcuisine.ie/
[twitterUrl] =>
[facebookUrl] =>
[ratings] =>
)
Here the hirerchy is:::
merchant->id (notice '0' is not present as any subarray index)
that's why should use
$merchantId = $results['merchant']['id'];
finally use can use code::
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $key=>$results) {
$discountPercent = $results['options'][0]['discountPercent'];
$discountPercent[] = $results['options'][0]['discountPercent'];//to get all in one;
$merchantId = $results['merchant']['id'];
$merchantId[] = $results['merchant']['id'];//to get all in one
echo $discountPercent.'<br>';
echo $merchantId;
}
?>

Related

How to add picture to database with laravel

I am creating Laravel 7 project and I want to add/browse images into/from MySQL database.
The images column names are icon_lg and icon_sm
This is my create function in the Controller I tried it in two ways as I saw in some tutorials:
public function create(Request $request)
{
$object = $this->objectModel::create([
'name' => $request->name,
'icon_sm' => $request->icon_sm
]);
if($request->hasFile('icon_lg')) {
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
It does nothing with icon_lg it inserts null value to it.
And it deals with icon_sm as String.
i think you must set the hasfile validation inside foreach loop like
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
if($request->hasFile('icon_lg')) {
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
just test it without validation first
it should work

Api Response and Json laravel format

I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS

Add key to multiple list of JSON

Using Laravel5.1 ...
I'm trying to convert this JSON:
"[{"John Doe":"john.gmail.com"},{"Frank Smith":"frank#frank.com"},{"Jie Brent":"jie#gmail.com"},{"Jeffrey Manney":"jeff17#gmail.com"}]"
To this:
"[{"name":"John Doe", "email":"john.gmail.com"},{"name":"Frank Smith", "email":"frank#frank.com"},{"name":"Jie Brent", "email":"jie#gmail.com"},{"name":"Jeffrey Manney", "email":"jeff17#gmail.com"}]"
This is my code:
$users_storage = [];
foreach($rcf_and_rcfm_users as $key => $user){
$users_storage[][$key] = $user;
}
$users = json_encode($users_storage);
dd($users);
The $rcf_and_rcfm_users variable is a collection of users from the database.
If I understand it correctly.
$users_storage = [];
foreach($rcf_and_rcfm_users as $name => $email){
$users_storage[] = [
'name' => $name,
'email' => $email,
];
}
$users = json_encode($users_storage);
dd($users);
I think this is what you're trying to accomplish.

wordpress json rest API to get custom field data

I am currently using the JSON REST API (WP API) plug-in to get my post and page data.
I have noticed that none of my custom field data is returned in the json, and looking at the routes, i don't think i can obtain these.
Any ideas via the current plug-in, or how I can accomplish this otherwise?
If you are using 'advanced custom fields' - until something more official is decided, you can use this plugin: https://github.com/times/acf-to-wp-api (and now on the shelf in standard wp plugin area too.)
It will include the custom fields under acf: [], in your json structure.
To grab a custom field value using native WP functions only, add the following to your functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Replace 'my_custom_field_key' with your custom field key name.
For multiple fields:
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
// My custom fields that I want to include in the WP API v2 responce
$fields = ['writer', 'publisher', 'year', 'youtube_link'];
foreach ( $fields as $field ) {
$_data[$field] = get_post_meta( $post->ID, $field, true );
}
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
You need to create this file contain following code in
wp-content\themes\name\inc\functions
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/*
* init function
*/
if ( ! function_exists( 'mnu_rest_init' ) ) {
function mnu_rest_init() {
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'GET',
'callback' => 'handle_get_all',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'POST',
'callback' => 'handle_post_booking',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
}
}
//GET QUERY PARMS
function handle_get_all( $request_data) {
$parameters = $request_data->get_params();
$userId = $parameters["Id"];
global $wpdb;
$query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
$list = $wpdb->get_results($query);
return $list;
}
// GET BODY PARMS
function handle_post_booking( $request_data) {
$parameters = $request_data->get_body();
$params = json_decode( $parameters , true );
// $userId = $parameters["Id"];
// global $wpdb;
// $query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
// $list = $wpdb->get_results($query);
return $params ;
}
then you need to add
//actions
add_action( 'rest_api_init', 'mnu_rest_init');
to your main.php in
wp-content\themes\name\inc\functions
to do that you need to require this file to main.php
require_once dirname( __FILE__ ) . '/filename.php';
You can manipulate the response and add custom fields to the JSON. I'm using Advanced Custom Fields in my example but you can just add any key/value-pairs to the data object before returning it.
// In functions.php
function modify_rest_post( $data, $post, $request ) {
if (is_admin()) {
return $data;
}
$data->my_favorite_data = get_field('my_custom_field', $post->ID);
return $data;
}
add_filter( 'rest_prepare_post', 'modify_rest_post', 10, 3 );

WordPress custom order filter by last name in post title

I have a custom post type for staff, that uses the post title as the persons name. In order to sort this by last name I'm using an order filter to find the last word in the title and then sort by it:
function posts_orderby_lastname ($orderby_statement)
{
$orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
return $orderby_statement;
}
This works great for most of the staff which have normal first and last names, but I can't figure out how would I do this for names like (all should be ordered by "Clause":
Santa Clause
Santa Clause III
Santa Clause Jr.
Santa Clause Kringle
M. Santa Clause Sr.
I assume I can have a stored array and then check for those terms (like "Jr.", "II", etc.) or check for the length of the term found is greater than maybe 3, but I have no idea how to implement that into the code. Any ideas or help would be greatly appreciated - thanks in advance!
I had a similar issue, this is how I solved it. You could expand on the if statement for all the edge cases you describe.
$args = array(
'post_type' => 'page',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'order' => 'ASC'
);
$posts = get_posts( $args );
// Order by second word in title, deal with edge cases
$lastname = array();
foreach( $posts as $key => $post ) {
$word = explode( ' ', $post->post_title );
$name = null;
if( strlen($word[1]) == 1 ) {
// Second word only 1 letter, so use third word if set
$name = $word[2];
} elseif( $word[3] == 'Sr.' ) {
// Third word is 'Sr.', so use 2nd word
$name = $word[1];
} else {
$name = $word[1];
}
$lastname[$key] = $name;
}
array_multisort( $lastname, SORT_ASC, $posts );
// Loop through posts
foreach( $posts as $post ) {
echo $post->post_title;
}
I slightly modified to fit my needs, because my names were like
Dawn A. Adelson
Timothy smith
John A. Smith, Jr.
$args = array(
'post_type' => 'YOUR_POST_TYPE',
'posts_per_page' => -1,
'order' => 'ASC'
);
$posts = get_posts( $args );
// Order by second word in title, deal with edge cases
$lastname = array();
foreach( $posts as $key => $post ) {
$word = explode( ' ', $post->post_title );
$name = null;
if( strlen($word[1]) == 2 ) {
// Second word 1 letter and dot, so use third word if set
$name = $word[2];
} elseif( $word[3] == 'Jr.' ) {
// Third word is 'Jr.', so use 2nd word
$name = $word[2];
} else {
$name = $word[1];
}
$lastname[$key] = $name;
}
array_multisort( $lastname, SORT_ASC, $posts );
// Loop through posts
foreach( $posts as $post ) {
?>
<div>
<?php echo $post->post_title; ?>
</div>
<?php
}
?>
</div>
Here's a way better approach, at least the other ones didn't work at all for me.
This will drop anything before the first space and apply a standard sort on the rest of the string. Make sure to modify is_main_query() and is_category() to your actual needs.
function posts_orderby_lastname( $orderby_statement )
{
if( is_main_query() && is_category() ) {
return "SUBSTRING_INDEX(post_title, ' ', -1)";
} else {
return $orderby_statement;
}
}
Try these plugins. It will help you.
http://wordpress.org/plugins/post-types-order/
http://wordpress.org/plugins/intuitive-custom-post-order/
http://wordpress.org/plugins/advanced-custom-sort/