How to merge two JSON Objects into one in php? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to merge two json objects into one ? both the json objects have similar structure
I have tried using below code , but its now working
<?php
$requestUrl="http://www.reddit.com/r/deals.json?limit=10&t=hour";
$requestUrl1="http://www.reddit.com/r/redditdeals.json?limit=10&t=hour";
$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);
$array1 = json_decode($data);
$array2 = json_decode($data1);
$json = json_encode(array_combine( $array1, $array2 )); //line 8
echo $json;
?>
EDIT : Sorry , Adding error details
Warning: array_combine() expects parameter 1 to be array, object given in "URL" on line 8
null
Edit : Adding JSON Objects $data and $data1 ( to keep it simple i just added only one item for object)
$data = '{
"kind": "Listing",
"data": {
"modhash": "ynp0pgdyf6bd03faef14e60cf6ab97f2e396bb81545ea57578",
"children": [
{
"kind": "t3",
"data": {
"domain": "self.deals",
"banned_by": null,
"media_embed": {
},
"subreddit": "deals",
"selftext_html": "<!-- SC_OFF --><div class=\"md\"><p>Some of you may have seen this already, but CreditSesame is running a promo for the month of November where you refer 6 friends and receive a $150 Amazon Gift Card. I&#39;m hoping we can get a legitimate referral train started so we can all make some easy money. Should come in handy for Christmas shopping.<\/p>\n\n<p>THIS OFFER IS FOR THE US ONLY &amp; YOU HAVE TO BE AT LEAST 18 YEARS OLD.<\/p>\n\n<p>What is CreditSesame?<\/p>\n\n<p>It&#39;s pretty much just like CreditKarma. It shows you your credit score, why you got the score and what you can do to improve it.<\/p>\n\n<p>Most importantly, there is NO CREDIT CARD NEEDED to sign up because it&#39;s FREE. You can of course buy some advanced features, but that&#39;s not necessary.<\/p>\n\n<p>Now, you do have to provide legitimate information, as it uses your SSN to get your credit report. They pull your credit report in a way that won&#39;t hurt your credit score according to their site. (Someone may be able to better explain this than me)<\/p>\n\n<p>Referral Train<\/p>\n\n<p>Here are some basic guidelines to try to get this thing running smoothly: Once you sign up, you can get your referral link by hovering over your name on in the top-right corner and selecting &quot;Invite a friend&quot; from the menu. Paste that link as a reply to who you signed up under in this thread. Each person only needs 6 referrals, so don&#39;t keep signing up under someone when they already have 6 replies. Keep &quot;forking&quot; and spreading the referrals around so that everyone has at least a chance to get a few. Please remove your referral link once you receive 6 referrals so everyone knows you have completed yours. So to get this started, here is my referral link and a non-ref link. If you would like to sign up under me, I would greatly appreciate it.<\/p>\n\n<p><a href=\"http:\/\/csesa.me\/?r=3RQho7mRN\">http:\/\/csesa.me\/?r=3RQho7mRN<\/a> (my link)<\/p>\n\n<p><a href=\"http:\/\/www.creditsesame.com\/\">http:\/\/www.creditsesame.com\/<\/a> (Non-ref)<\/p>\n\n<p>Mods, I have read over the rules and I don&#39;t think I&#39;m breaking any. Please let me know if I am or delete the thread if this is not allowed. Thanks!<\/p>\n<\/div><!-- SC_ON -->",
"selftext": "Some of you may have seen this already, but CreditSesame is running a promo for the month of November where you refer 6 friends and receive a $150 Amazon Gift Card. I'm hoping we can get a legitimate referral train started so we can all make some easy money. Should come in handy for Christmas shopping.\n\nTHIS OFFER IS FOR THE US ONLY &amp; YOU HAVE TO BE AT LEAST 18 YEARS OLD.\n\nWhat is CreditSesame?\n\nIt's pretty much just like CreditKarma. It shows you your credit score, why you got the score and what you can do to improve it.\n\nMost importantly, there is NO CREDIT CARD NEEDED to sign up because it's FREE. You can of course buy some advanced features, but that's not necessary.\n\nNow, you do have to provide legitimate information, as it uses your SSN to get your credit report. They pull your credit report in a way that won't hurt your credit score according to their site. (Someone may be able to better explain this than me)\n\nReferral Train\n\nHere are some basic guidelines to try to get this thing running smoothly: Once you sign up, you can get your referral link by hovering over your name on in the top-right corner and selecting \"Invite a friend\" from the menu. Paste that link as a reply to who you signed up under in this thread. Each person only needs 6 referrals, so don't keep signing up under someone when they already have 6 replies. Keep \"forking\" and spreading the referrals around so that everyone has at least a chance to get a few. Please remove your referral link once you receive 6 referrals so everyone knows you have completed yours. So to get this started, here is my referral link and a non-ref link. If you would like to sign up under me, I would greatly appreciate it.\n\nhttp:\/\/csesa.me\/?r=3RQho7mRN (my link)\n\nhttp:\/\/www.creditsesame.com\/ (Non-ref)\n\nMods, I have read over the rules and I don't think I'm breaking any. Please let me know if I am or delete the thread if this is not allowed. Thanks!",
"likes": null,
"user_reports": [
],
"secure_media": null,
"link_flair_text": null,
"id": "2m366z",
"gilded": 0,
"secure_media_embed": {
},
"clicked": false,
"report_reasons": null,
"author": "EarthBrown",
"media": null,
"score": 5,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "self",
"subreddit_id": "t5_2qir9",
"edited": false,
"link_flair_css_class": null,
"author_flair_css_class": null,
"downs": 0,
"mod_reports": [
],
"saved": false,
"is_self": true,
"name": "t3_2m366z",
"permalink": "\/r\/deals\/comments\/2m366z\/free_150_for_6_referrals_to_credit_sesame\/",
"stickied": false,
"created": 1415840944,
"url": "http:\/\/www.reddit.com\/r\/deals\/comments\/2m366z\/free_150_for_6_referrals_to_credit_sesame\/",
"author_flair_text": null,
"title": "Free $150 for 6 Referrals to Credit Sesame!",
"created_utc": 1415812144,
"ups": 5,
"num_comments": 2,
"visited": false,
"num_reports": null,
"distinguished": null
}
}],
"after": "t3_2lx2yh",
"before": null
}
}';
$data1 = '{
"kind": "Listing",
"data": {
"modhash": "mxgmpcysk5ce5f6dbb57adcc895d089f0fc5c98d08361beb37",
"children": [
{
"kind": "t3",
"data": {
"domain": "rodneybrooksjr.com",
"banned_by": null,
"media_embed": {
},
"subreddit": "redditdeals",
"secure_media": null,
"link_flair_text": null,
"id": "2d5ad3",
"gilded": 0,
"secure_media_embed": {
},
"clicked": false,
"report_reasons": null,
"author": "rodneybrooksjr",
"media": null,
"score": 0,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "",
"subreddit_id": "t5_2r0ax",
"edited": false,
"link_flair_css_class": null,
"author_flair_css_class": null,
"downs": 0,
"mod_reports": [
],
"saved": false,
"is_self": false,
"name": "t3_2d5ad3",
"permalink": "\/r\/redditdeals\/comments\/2d5ad3\/heres_a_product_i_like_that_you_might_want_to\/",
"stickied": false,
"created": 1407682429,
"url": "http:\/\/rodneybrooksjr.com\/kingston",
"author_flair_text": null,
"title": "Here's a product I like that you might want to check out! You can get Kingston 4GB USB Flash Drive for just $9.97 (a 44% savings!)",
"created_utc": 1407678829,
"ups": 0,
"num_comments": 1,
"visited": false,
"num_reports": null,
"distinguished": null
}
}],
"after": "t3_1zqtxs",
"before": null
}
}';
Am i doing something wrong ? Thanks in advance

Instead of array_combine which combines values in array1 as key and values from array2 as value you should use array_merge($array1, $array2) to merge two arrays

Related

Microsoft Graph API : Get Tasks of users in a group with PHP

Hi I am trying to build a Dashboard that show summary of what happens in a Planner Plan, Calendar events and SharePoint files etc. I want to show users' task in different tables. I have managed to authorize and get the user list and get the all tasks from a plan by following the documentation. But the tasks I get returns something like this. I can see the task is assigned to "9d2e533d-6e8e-xxx-8959-846xxxbe192ab" but how do I get/print this? I can get the task title by using getTitle() method. But how do I getthe assignee? Or is there a better way to get tasks based on users?
{
"#odata.etag": "W/\"JzEtVGFzayxxBAxAQxxxEBAWCc=\"",
"planId": "UeRhlCyHxxxxxk3CpgABpFg",
"bucketId": "GWqGxxxxak-YzYxxx0-bm-5xxxxzZ9",
"title": "Arge 2",
"orderHint": "85xxx467xxxx41871P|",
"assigneePriority": "",
"percentComplete": 50,
"startDateTime": null,
"createdDateTime": "2020-06-14T12:54:41.8747394Z",
"dueDateTime": null,
"hasDescription": false,
"previewType": "automatic",
"completedDateTime": null,
"completedBy": null,
"referenceCount": 0,
"checklistItemCount": 0,
"activeChecklistItemCount": 0,
"conversationThreadId": null,
"id": "8BxxxtlHQxxxGPR0xxxgAMfWV",
"createdBy": {
"user": {
"displayName": null,
"id": "75c90cdf-a9fc-4f55-860a-87076b9a31ef"
}
},
"appliedCategories": {},
"assignments": {
"9d2e533d-6e8e-xxx-8959-846xxxbe192ab": {
"#odata.type": "#microsoft.graph.plannerAssignment",
"assignedDateTime": "2020-06-14T13:02:07.0513638Z",
"orderHint": "858609xxxxx8441xxx388P#",
"assignedBy": {
"user": {
"displayName": null,
"id": "75cx0cdf-a9fc-4xxx-860a-87xxxx9a31ef"
}
}
}
}
},
That is the user id of the assignee, you can get information about the user through Get User request. More efficiently, you can get the group members, and match the id of the user to Group membership which includes basic user info. It is possible to have assignees that are not members of the group, so you should use membership when available and fallback to user info otherwise to get the complete data efficiently.

Google Books API Limit Results

Is there any way to limit the results returned by the Google Books API?
For example the following URL:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310
Returns the following:
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "ofTsHAAACAAJ",
"etag": "K6a+5IuCMD0",
"selfLink": "https://www.googleapis.com/books/v1/volumes/ofTsHAAACAAJ",
"volumeInfo": {
"title": "Panic",
"authors": [
"Jeff Abbott"
],
"publisher": "Grand Central Publishing",
"publishedDate": "2006",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0751538310"
},
{
"type": "ISBN_13",
"identifier": "9780751538311"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 408,
"printType": "BOOK",
"categories": [
"Austin (Tex.)"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/Panic.html?hl=&id=ofTsHAAACAAJ"
},
"saleInfo": {
"country": "GB",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "GB",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.co.uk/books/reader?id=ofTsHAAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
Is there any way I can return only the title and description? I think it may improve performance of my web application.
I have looked at the partial response but it doesn't seem to work.
I am including my API key in the URL query parameter.
Thanks
I added the params according to the partial response documentation.
See the params in following link:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310&fields=items(volumeInfo/description,volumeInfo/title)
It will return:
{
"items": [
{
"volumeInfo": {
"title": "Panic",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
}
maxResults
include this in your query. 5 is just an integer.
&maxResults=5
Google will help you create your API with this website API called try it.
https://developers.google.com/books/docs/v1/reference/volumes/list?apix=true#try-it
Maybe its too late to respond but you need to activate the API before accessing it. When you try to access it says to activate it from console with some project id. Just copy that url and it takes you straight to your dashboard where you can find your activation button post which you can access the partial response with desired attributes.

Lottery on wordpress using php and json

I am currently building a website for my guild (on a video game).
The video game (Guild wars 2) provide us a feed of everything being done inside the guild in a json file (user joining, withdraw of money, deposit of items, kick, etc...).
Since I have this feed, auto-updated, I would like to setup a lottery, working on the following :
- guild member (user) buy a ticket => deposit golds in our bank (displayed as deposit)
- display this information on the website => user "x" has bought a ticket at H:M:DD:MM:Y (for example)
- at the end of the month, script to random a winner from this list of users (this random must include only tickets bought between date A & B)
I have managed to write a little code, and it is working, only to display a list of users and their actions :
<?php
$apikey = '(My API key)';
$guildkey = '(My guild key)';
$jsontest =file_get_contents ('https://api.guildwars2.com/v2/guild/'.$guildkey.'/log?access_token='. $apikey);
$json = json_decode($jsontest,true);
foreach($json as $member)
{
if ($member['coins'] > 1)
print "Guild member "."".$member['user'].""." has bought a ticket for ".$member['coins']." golds"." ";
}
?>
Here a little example of how the guild wars 2 api output is :
{
"type": "upgrade",
"item_id": 77729,
"count": 1,
"action": "completed",
"id": 896815,
"time": "2017-02-23T14:26:29.000Z",
"user": "Lehi.5091",
"upgrade_id": 668
},
{
"id": 896814,
"time": "2017-02-23T14:26:29.000Z",
"type": "upgrade",
"upgrade_id": 668,
"action": "queued"
},
{
"type": "upgrade",
"item_id": 77729,
"count": 1,
"action": "completed",
"id": 896810,
"time": "2017-02-23T14:26:28.000Z",
"user": "Lehi.5091",
"upgrade_id": 668
As intended, it does display what I want, here the working code
If you have tips or anything about how to this, I'll gladly take them.
Thanks for your help,

Contact creation through Graph API producing "Object reference not set to an instance of an object."

I've been using the Graph API for contact creation and synchronization between a master account and all of our organization's Office 365 accounts. This has been working well up until the past month or so.
My synchronization process involves querying a specific folder of the master account for contacts, caching them, and then running through the list of target users, creating contacts where necessary. Getting lists of contacts, creating contact folders, and deleting contacts all still works as expected. Creating a contact returns "ErrorInternalServerError: Object reference not set to an instance of an object."
I have been using the client_credentials flow and checked that my app has the appropriate credentials in the Azure AD admin panel. Below is the JSON object that I'm POSTing for contact creation. This is happening regardless of contact, or target user.
{
"categories": [],
"birthday": null,
"fileAs": "GPS 00 Bob, Todd",
"displayName": "GPS 00 Bob, Todd",
"givenName": "Todd",
"initials": "T.G.0.B.",
"middleName": "",
"nickName": null,
"surname": "GPS 00 Bob",
"title": "",
"yomiGivenName": null,
"yomiSurname": null,
"yomiCompanyName": null,
"generation": "",
"emailAddresses": [
{
"name": "Email",
"address": "todd.bob#contactsyncing.com"
}
],
"imAddresses": [
""
],
"jobTitle": "Chief Financial Officer",
"companyName": "",
"department": "",
"officeLocation": null,
"profession": null,
"businessHomePage": null,
"assistantName": null,
"manager": null,
"homePhones": [
""
],
"mobilePhone": "",
"businessPhones": [
""
],
"homeAddress": {
"street": "",
"city": "",
"state": "",
"countryOrRegion": "",
"postalCode": ""
},
"businessAddress": {
"street": "701 East Lumbar Ave",
"city": "Minot",
"state": "ND",
"countryOrRegion": "United States of America",
"postalCode": "68745"
},
"otherAddress": {},
"spouseName": null,
"personalNotes": null,
"children": []
}
edit
Additional information: I am posting to a specific contact folder with its ID. Here is an example of the URL: https://graph.microsoft.com/v1.0/users/91bbdb7b-3b41-474c-93c9-99b1da960c18/contactFolders/AAMkADFlNzQ5NGQ5LTEwNjYtNGFiZS04NDlhLTViOGE0YzMzZjI3OQAuAAAAAAA9YtgrncHYSKObisZl7JkCAQChpNwDV4FXRaJC6UF1HyyuAAAAAAFFAAA=/contacts
Is that contactFolder ID properly formed?
/edit
The script is written in PHP and I'm simply cURLing these requests. Any thoughts are suggestions would be greatly appreciated. Let me know if any other information would be helpful.
Thanks!
After filtering down contact fields to a bare minimum and then re-adding them one by one, I've found that the birthday field was at fault. It seems that the Graph API no longer accepts a null value for this. Removing the field completely if a birthday is not specified seems to have resolved the issue.
I consider this resolved. Perhaps the Graph API documentation should be updated to reflect this fact? Additionally, it would seem prudent to improve the API's response to this error. "InternalServerError" does not adequately describe the cause.
Thanks!

Make variables from JSON array from Stripe

I am using PHP to return an array for a customer object in Stripe. Here's an example of what this array looks like:
Stripe\Customer JSON: {
"id": "censored",
"object": "customer",
"account_balance": 0,
"created": 1447428085,
"currency": "usd",
"default_source": "censored",
"delinquent": false,
"description": "From website",
"discount": null,
"email": "email#email.com",
"livemode": false,
"metadata": {
"First_Last": "asdf asdf",
"Info": "|Make: maketest |Model: modeltest |serial: 1 |YOM: 1999",
"Shipping_firstaddr": "asdf asdf",
"Shipping_lastaddr": "asdf",
"Shipping_country": "CA",
"Shipping_zip": "asdf",
"Shipping_city": "asdf",
"Shipping_states": "AK",
"Shipping_mobile": "asdf",
"Same_as_billing?": "Yes",
}
}
I now need to pull out the values in metadata->Info such that each item inbetween the pipes is a variable with a value. For example, it would be ideal to have a variable, like $make, equal the value in the pipe, in this case "maketest".
EDIT: Thus far I have isolated the "Info" from the array into a variable. If I were to echo that variable it would say "|Make: maketest |Model: modeltest |serial: 1 |YOM: 1999"
EDIT 2: I have not yet tried any code to do anything with this variable. Honestly, I don't know where to start. RegEx? I don't know RegEx, but happy to learn if that's best.
EDIT 3: So I did google stuff before posting this, but I couldn't find the right thing. Thanks to help from comments I googled the right thing and figured out a solution that will work.
I am using this code to list things out into variables and it works!
$info is a variable that has the "Info" from the metadata, so echo'd it would be "|Make: maketest |Model: modeltest |serial: 1 |YOM: 1999"
Then just do
list($Make, $Model,$Serial, $YOM)=explode('|',$info);
var_dump($Make);
var_dump($Model);
var_dump($Serial);
var_dump($YOM);
This results in listing these variables such that $Make = "Make: maketest"
It's not ideal, but I can work with this.

Categories