get following nested array webservice in php using the mysql database - php

"data":{
"2":{
"sub_category_id":"1",
"product":[
{
"sub_category_id":"1",
"product_id":"1",
"product_name":"American"
},
{
"sub_category_id":"1",
"product_id":"34",
"product_name":"Ausi Product"
}
]
},
"3":{
"sub_category_id":"2",
"product":{
"2":{
"sub_category_id":"2",
"product_id":"2",
"product_name":"Canadian"
}
}
}
}
What i excepted result:
"data":[
"2":{
"sub_category_id":"1",
"product":[
{
"sub_category_id":"1",
"product_id":"1",
"product_name":"American"
},
{
"sub_category_id":"1",
"product_id":"34",
"product_name":"Ausi Product"
}
]
},
"3":{
"sub_category_id":"2",
"product":[
"2":{
"sub_category_id":"2",
"product_id":"2",
"product_name":"Canadian"
}
]
]
i.e. i wantel [] after data and product.

You can instruct the PHP json_decode() function to parse objects into associative arrays.
$parsedJSON = json_decode($jsonString, /* $assoc = */ true)

Related

How I can read and update the nested JSON in PHP

I am new to PHP and have little experience with PHP arrays, I have this below JSON file.
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
I want to update the values for 'location', 'vmSize','sku','publisher','offer' in the above JSON,
"location" : "eastus"
"vmSize" : "Standard_D3_v2"
"sku" : "20h1-evd"
"publisher" : "MicrosoftWindowsDesktop"
"offer" : "windows-10"
I have tried to do the following to this but I am nowhere near navigating the array correctly.
$arr = json_decode($json2, true);
print_r($arr);
Can anyone please help here?
Just try this code
<?php
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
$arr = json_decode($json2, true);
$arr['location'] = "eastus";
$arr['properties']['hardwareProfile']['vmSize'] = "Standard_D3_v2";
$arr['properties']['storageProfile']['imageReference']['sku'] = "20h1-evd";
$arr['properties']['storageProfile']['imageReference']['publisher'] = "MicrosoftWindowsDesktop";
$arr['properties']['storageProfile']['imageReference']['offer'] = "WindowsServer";
$updatedJson = json_encode($arr);
print_r($updatedJson);
First you need to try json_decode to make an array from this json file and then based on the array schema you need to find the property that you want and update it and then again use the json_encode to make an json

How to make dynamic elastic search query based on my given input values in Elastic Search

I have written elastic search query in static values, now i want to make as a dynamic like i have input fields, based on the input values i have to make my dynamic elastic search query. how can i do it? any one please update my answer.
INPUT
{
"userID" : "USER1",
"groupID" : "5b278f8856db693c457b4697",
"contentType " : "question",
"contentID" : "5",
"contentFlow": [
{
"contentId": "123",
"contentType": "topic"
},
{
"contentId": "456",
"contentType": "concept"
},
{
"contentId": "100",
"contentType": "sdl"
}
]
}
STATIC QUERY
{
"size":999,
"query":{
"bool":{
"must":[
{
"term":{
"userId":"USER1"
}
},
{
"term":{
"contentId":"5"
}
},
{
"bool":{
"must":[
{
"term":{
"contentPath.contentType":"topic"
}
},
{
"term":{
"contentPath.contentId":"123"
}
}
]
}
},
{
"bool":{
"must":[
{
"term":{
"contentPath.contentType":"concept"
}
},
{
"term":{
"contentPath.contentId":"456"
}
}
]
}
},
{
"bool":{
"must":[
{
"term":{
"contentPath.contentType":"sdl"
}
},
{
"term":{
"contentPath.contentId":"100"
}
}
]
}
}
]
}
}
}
I am new to learning elastic search, kindly help me out on this problem

How to get key 'errors' of this data type in PHP

I have data type like below. But I want to get the 'errors' key and 'errors.message' value.
[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]
I have tried to store the code in variable ($get_errors) and then call 'errors' key like this. but the code is not working.
return $get_errors['errors'];
return $get_errors->errors;
Thanks.
Try to convert your JSON data to array then fetch the desired result from the array Try the following maybe it's work for you
$getError = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$array_getError = json_decode($getError,true);
var_dump($array_getError[0]["errors"]);
This is Json type. So you have to decode json. Then you can geta data from it
$json = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$data = json_decode($json,true);
echo $data[0]['errors']['message'];
DEMO
$x = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$errors = (json_decode($x)[0]->errors);

I have trouble reading a particular array in a JSON feed

I use json_decode() to parse a json feed and everything works just fine until I come to the array (media) that keeps digits as key instead of letters. I have tryed everything but all I get is different errors when it comes to this array (media)
The media array contains links to images and I just need the first image in every media array really. But the array can keep random digits in different order for the image links.
But the main problem is that I can't print this key, even if I know the name of it is "10" for example.
My second problem is that I never know the digits of the first image.
I would be very grateful if I can get help with this.
My code:
$data = json_decode($json_obj);
foreach($data->events as $event) {
echo $event->eventDateTime.'<br>'; //works
echo $event->eventId.'<br>'; //works
echo $event->title->eventTitleText.'<br>'; //works
echo strtoupper($event->venue->city).'<br>'; //works
echo $event->venue->title.'<br>'; //works
echo $event->ticketing->url.'<br>'; //works
echo $event->media->10.'<br>'; // Does NOT work
}
Below is a complete json feed that contains just 1 event.
{
"meta":{
"total":117,
"locale":"en-US",
"page":1,
"rows":1
},
"events":[
{
"-----":"252975",
"modifiedUTC":"2014-08-29T17:23:21",
"locale":"en-US",
"localeAvailable":{
"1":"sv-SE"
},
"title":{
"presentedBy":null,
"headliners":"<a href=\"http:\/\/www....\/artists\/251396\/djurgarden-hockey\">Djurg\u00e5rden Hockey<\/a> - Eisb\u00e4ren Berlin",
"supporting":null,
"supportingText":null,
"tour":"Champions Hockey League",
"eventTitle":"<a href=\"http:\/\/www....\/artists\/251396\/djurgarden-hockey\">Djurg\u00e5rden Hockey<\/a> - Eisb\u00e4ren Berlin",
"eventTitleText":"Djurg\u00e5rden Hockey - Eisb\u00e4ren Berlin"
},
"age":null,
"currency":"SEK",
"currencySymbol":null,
"eventDateTime":"2014-09-05T20:05:00",
"eventDateTimeZone":"Europe\/Stockholm",
"eventDateTimeUTC":"2014-09-05T18:05:00",
"eventDateTimeISO":"2014-09-05T20:05:00+02:00",
"dateOnly":false,
"additionalDates":[
],
"doorDateTime":null,
"doorDateTimeUTC":null,
"announceDateTime":"2014-08-04T10:00:00",
"announceDateTimeTimeZone":"Europe\/Stockholm",
"announceDateTimeUTC":"2014-08-04T08:00:00",
"presaleDateTime":null,
"presaleDateTimeTimeZone":null,
"presaleDateTimeUTC":null,
"presaleEndDateTime":null,
"presaleEndDateTimeTimeZone":null,
"presaleEndDateTimeUTC":null,
"onsaleDateTime":"2014-08-06T09:00:00",
"onsaleDateTimeTimeZone":"Europe\/Stockholm",
"onsaleDateTimeUTC":"2014-08-06T07:00:00",
"ticketing":{
"statusId":1,
"status":"Buy Tickets",
"callToAction":"Get your tickets today!",
"callToActionEnabled":false,
"url":"http:\/\/www....\/events\/252975\/djurgarden-hockey-eisbaren-berlin-tickets",
"eventUrl":"http:\/\/www....\/events\/252975\/djurgarden-hockey-eisbaren-berlin-tickets",
"ticketLinkExists":true
},
"ticketPrice":"120.00 kr - 170.00 kr",
"doorPrice":null,
"bio":null,
"description":null,
"minorCategoryId1":"34",
"minorCategoryId2":null,
"minorCategoryId3":null,
"majorCategoryId1":"3",
"majorCategoryId2":null,
"majorCategoryId3":null,
"venue":{
"venueId":"101916",
"locale":"en-US",
"localeAvailable":{
"1":"en-US",
"2":"sv-SE"
},
"title":"Hovet",
"address_line":"Globentorget 2, Stockholm, Sweden 121 27",
"address":"Globentorget 2",
"city":"Stockholm",
"state":null,
"postalCode":"121 27",
"country":"Sweden",
"url":"http:\/\/www....\/venues\/101916\/hovet-stockholm-tickets",
"urlSlug":"hovet-stockholm-tickets",
"venueUrl":"http:\/\/www.globearenas.se\/archive\/pages\/18711\/hovet.aspx",
"phone1":"0771-31 00 00",
"phone2":null,
"alias":null,
"parking":null,
"boxOffice":null,
"directions":null,
"longitude":"18.0808159",
"latitude":"59.2941674",
"timezone":"Europe\/Stockholm",
"ada":null,
"keywords":[
],
"skinCode":"sga",
"currency":"SEK",
"media":{
"10":{
"media_id":"29254",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/10-08172012-502e82fe803bf.jpeg"
},
"11":{
"media_id":"29256",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/11-08172012-502e82fe8f5a7.jpeg"
},
"14":{
"media_id":"29258",
"width":608,
"height":252,
"file_name":"http:\/\/........net\/14-08172012-502e83abb9512.jpeg"
},
"12":{
"media_id":"29255",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/12-08172012-502e82fe88c58.jpeg"
}
},
"links":[
{
"link_id":976779,
"link_title":null,
"link_type_id":"23",
"link_href":"http:\/\/www.marriott.com\/search\/submitSearch.mi?searchType=InCity&formType=InCity&marriottBrands=BR&destinationAddress.city=Stockholm&destinationAddress.stateProvince=&destinationAddress.country=SE"
}
]
},
"tour":[
],
"promoters":null,
"associations":{
"performerIds":[
"251396"
],
"headliners":[
{
"performerId":"251396",
"locale":"en-US",
"localeAvailable":{
"1":"en-US"
},
"name":"Djurg\u00e5rden Hockey",
"minorCategoryText":"Hockey",
"minorCategoryId":"34",
"minorCategory1Id":"34",
"minorCategory2Id":null,
"minorCategory3Id":null,
"minorCategoryUrl":"http:\/\/www....\/browse\/sports\/hockey",
"majorCategoryText":"Sports",
"major_category_id":"3",
"majorCategory1Id":"3",
"majorCategory2Id":null,
"majorCategory3Id":null,
"majorCategoryUrl":"http:\/\/www....\/browse\/sports",
"keywords":[
"DIF",
"Djurgarden"
],
"bio":null,
"shortBio":null,
"aliases":null,
"url":"http:\/\/www....\/artists\/251396\/djurgarden-hockey-tickets",
"urlSlug":"djurgarden-hockey-tickets",
"media":{
"7":{
"media_id":"149467",
"width":220,
"height":220,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_7_5294e45990e1f.jpg"
},
"24":{
"media_id":"149463",
"width":322,
"height":322,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_24_5294e45974caa.jpg"
},
"6":{
"media_id":"149465",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_6_5294e459867f5.jpg"
},
"5":{
"media_id":"149466",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_5_5294e4598bec3.jpg"
},
"9":{
"media_id":"149464",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_9_5294e45981552.jpg"
}
},
"events":[
],
"links":[
{
"link_id":976320,
"link_title":null,
"link_type_id":"13",
"link_href":"https:\/\/twitter.com\/difhockeyse"
},
{
"link_id":976321,
"link_title":null,
"link_type_id":"12",
"link_href":"https:\/\/www.facebook.com\/DJURGARDEN"
}
]
}
],
"supportingActs":[
]
},
"media":[
],
"relatedMedia":{
"1":{
"media_id":"149466",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_5_5294e4598bec3.jpg"
},
"2":{
"media_id":"149465",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_6_5294e459867f5.jpg"
},
"3":{
"media_id":"149467",
"width":220,
"height":220,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_7_5294e45990e1f.jpg"
},
"4":{
"media_id":"149464",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_9_5294e45981552.jpg"
},
"23":{
"media_id":"149463",
"width":322,
"height":322,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_24_5294e45974caa.jpg"
},
"17":{
"media_id":0,
"width":"678",
"height":"399",
"file_name":"http:\/\/dc1tv648rdvbu.....net\/...\/bundles\/aeg...\/images\/defaults\/1\/1_678_399.png"
},
"18":{
"media_id":0,
"width":"564",
"height":"564",
"file_name":"http:\/\/dc1tv648rdvbu.....net\/...\/bundles\/aeg...\/images\/defaults\/1\/1_564_564.png"
}
},
"links":[
{
"link_id":976321,
"link_title":null,
"link_type_id":"12",
"link_href":"https:\/\/www.facebook.com\/DJURGARDEN"
},
{
"link_id":976320,
"link_title":null,
"link_type_id":"13",
"link_href":"https:\/\/twitter.com\/difhockeyse"
}
]
}
]
}
You need to use curly braces:
echo $event->media->{10}->width;
If you do not know what the properties will be called, you can iterate them in a nested loop:
foreach($event->media as $media){
echo $media->width . '<br/>';
}
To just get the 1st property, if you do not intend to iterate them, you can use reset():
$first = reset($event->media);
echo $first->width;
Live (updated) example: http://codepad.viper-7.com/IU2wCy

I cannot seem to get data into JSON correctly

Hello I have spent quite bit of time trying to get my data to look like this in JSON as a sample:
var json = {
"id": "347_0",
"name": "Nine Inch Nails",
"children": [{
"id": "126510_1",
"name": "Jerome Dillon",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": [{
"id": "52163_2",
"name": "Howlin' Maggie",
"data": {
"band": "Jerome Dillon",
"relation": "member of band"
},
"children": []
}, {
"id": "324134_3",
"name": "nearLY",
"data": {
"band": "Jerome Dillon",
"relation": "member of band"
},
"children": []
}]
}, {
"id": "173871_4",
"name": "Charlie Clouser",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": []
}, {
"id": "235952_5",
"name": "James Woolley",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": []
},
I am using the json_encode function and I know how to make the data into JSON I just cannot seem to create anything that will output the above JSON format...For example I use the following code:
foreach($relations as $rel){
$data[$id]["relationTo"] = $rel["name"];
$data[$id]["relation"] = $rel["relation"];
$id = $id + 1;
}
$id = 0;
foreach($relations as $rel){
$children[$id]["id"] = $id+1;
$children[$id]["name"] = $rel["sname"];
$children[$id]["data"] = $data[$id];
$id = $id + 1;
}
$relationsArray["id"] = 0;
$relationsArray["name"] = $rel["name"];
$relationsArray["children"] = $children;
$json_content = json_encode($relationsArray);
And this outputs:
"id":0,
"name":"Al",
"children":[
{
"id":1,
"name":"Brandon",
"data":{
"relationTo":"Albaraa",
"relation":"Friend"
},
"children":[
]
},
{
"id":2,
"name":"Shen",
"data":{
"relationTo":"Albaraa",
"relation":"Friend"
},
"children":[
]
},
{
"id":3,
"name":"Dan",
"data":{
"relationTo":"Albaraa",
"relation":"Professor"
},
"children":[
]
},
{
"id":4,
"name":"Bob",
"data":{
"relationTo":"Albaraa",
"relation":"Boss"
},
"children":[
]
},
{
"id":5,
"name":"Al",
"data":{
"relationTo":"Albaraa",
"relation":"God Father"
},
"children":[
]
},
{
"id":6,
"name":"Albaraa",
"data":{
"relationTo":"Shen",
"relation":"Friend"
},
"children":[
]
},
{
"id":7,
"name":"Brandon",
"data":{
"relationTo":"Shen",
"relation":"Friend"
},
"children":[
]
},
{
"id":8,
"name":"Dan",
"data":{
"relationTo":"Shen",
"relation":"Professor"
},
"children":[
]
},
{
"id":9,
"name":"Albaraa",
"data":{
"relationTo":"Al",
"relation":"God Son"
},
"children":[
]
},
{
"id":10,
"name":"Bob",
"data":{
"relationTo":"Al",
"relation":"Best Friends"
},
"children":[
]
}
]
}
and so on...but I am not able to get the children of the children as you see above!
Any help would be amazing thank you!
EDIT:
class Child{
public $id;
public $name;
public $children;
public $data;
public function __construct($id, $sname, $data, $rel){
$this->children = array();
$this->data = array();
if ($rel){
$this->id = $id+1;
$this->name = $sname;
$data = array();
$data["relationTo"] = $rel["name"];
$data["relation"] = $rel["relation"];
$this->children[] = new Child($id, $rel["sname"],$data);
}
else {
$this->id = $id+1;
$this->name = $sname;
$this->data = $data;
}
}
}
$childrel = array();
$id = 0;
foreach($relations as $rel){
$childrel[] = new Child($id ,"","", $rel);
$id = $id + 1;
}
You have not declared $children before assigning values to it before foreach loop. Hence declare the array like this and alter the code to this
$children = array();
$id = 0;
foreach($relations as $rel){
$children[$id]["id"] = $id+1;
$children[$id]["name"] = $rel["sname"];
$children[$id]["data"] = $data[$id];
$id = $id + 1;
}

Categories