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
Related
I have a JSON file that have all list of all the countries with their cities, and state. The file has this structure
"NO": {
"name": "Norway",
"states": {
"VA": {
"name": "Vest-Agder"
},
"RO": {
"name": "Rogaland"
},
"HO": {
"name": "Hordaland"
},
"SF": {
"name": "Sogn og Fjordane"
},
"MR": {
"name": "Møre og Romsdal"
},
"ST": {
"name": "Sør-Trøndelag"
},
"NO": {
"name": "Nord-Trøndelag"
},
"NT": {
"name": "Nordland"
},
"TR": {
"name": "Troms"
},
"FI": {
"name": "Finnmark"
},
"SJ": {
"name": "Svalbard"
},
"SJ": {
"name": "Jan Mayen"
},
"AK": {
"name": "Akershus"
},
"AA": {
"name": "Aust-Agder"
},
"BU": {
"name": "Buskerud"
},
"HE": {
"name": "Hedmark"
},
"OP": {
"name": "Oppland"
},
"OS": {
"name": "Oslo"
},
"TE": {
"name": "Telemark"
},
"VF": {
"name": "Vestfold"
},
"OF": {
"name": "Østfold"
}
}
},
What I am trying to achieve is to get the short name of state when user input the full name in the input field. For example if they add "Oslo" I will get "OS" in output
This is the code that I came up with but I am not getting the output.
$jsonitem = file_get_contents("countries-info.json");
$objitems = json_decode($jsonitem);
$findByname = function($name) use ($objitems) {
foreach ($objitems as $friend) {
if ($friend->name == $name) return $friend->state;
}
return false;
};
echo $findByname($_GET[code]) ?: 'No record found.';
Need advise.
Looking at the structure of your JSON you should loop $objitems->NO->states ( $objitems will contain the complete object, you only want the states)
So you need to change your foreach to:
foreach ($objitems->NO->states as $short => $state) {
if ($state->name == $name) return $short;
}
foreach ($objitems as $state => $friend) {
if ($friend->name == $name) return $state;
}
I want to get the names values from a JSON array.
{
"workspaces": {
"workspace": [
{
"name": "SITR",
"href": "http://localhost:8080/geoserver/rest/workspaces/SITR.json"
},
{
"name": "fire",
"href": "http://localhost:8080/geoserver/rest/workspaces/fire.json"
},
{
"name": "info-geospasial",
"href": "http://localhost:8080/geoserver/rest/workspaces/info-geospasial.json"
},
{
"name": "pertanian",
"href": "http://localhost:8080/geoserver/rest/workspaces/pertanian.json"
},
{
"name": "semangat21",
"href": "http://localhost:8080/geoserver/rest/workspaces/semangat21.json"
},
{
"name": "semangat",
"href": "http://localhost:8080/geoserver/rest/workspaces/semangat.json"
},
{
"name": "cobalagi",
"href": "http://localhost:8080/geoserver/rest/workspaces/cobalagi.json"
},
{
"name": "cobak",
"href": "http://localhost:8080/geoserver/rest/workspaces/cobak.json"
}
]
}
}
I have tried this following
$responsArray=json_decode($res->getBody());
dd($responsArray->workspaces->workspace->name);
but it return 'trying to access the property of a non-object'.
Anyone can help ?
I am so appreciated and thank you
Convert all object levels to multidimensional associative array structure passing true flag as second argument of json_decode() function and then access it like accessing to multidimensional array:
$nameArr = [];
$responseArray = json_decode($res->getBody(), true); // set true here
foreach ($responseArray['workspaces']['workspace'] as $row) {
$nameArr[] = $row['name'];
}
dd($nameArr);
$nameArr = [];
$responsArray=json_decode($res->getBody());
foreach($responsArray->workspaces->workspace as $row)
{
$nameArr[] = $row->name;
}
dd($nameArr);
This question already has answers here:
PHP multidimensional array get value by key
(2 answers)
Closed 4 months ago.
I have a JSON array as follows:
[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]
I want to loop through this nested JSON array to retrieve all the "desc" from the "custClass" list using PHP.
Any help would be appreciated.
You can try this way
$json='{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}';
$decode=json_decode($json,true);
$desc=[];
foreach($decode['custClass'] as $cust){
$desc[]=$cust['desc'];
}
var_dump($desc);
You can decode data and loop it
$s = '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
$data =json_decode($s,true);
foreach($data as $obj){
foreach($obj['custClass'] as $val){
echo "Desc ".$val['desc']."<br/>";
}
}
Try decoding data and retrieve it using foreach:
$your_data = your_data;
$decoded_data = json_decode($your_data [0], true);
$final_data = [];
foreach($decoded_data['custClass'] as $data) {
$final_data[] = $data['desc'];
}
print_r($final_data);
try this code
loop this array like below
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
json_decode() the data
<?php
$data= '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
?>
You can loop through all JSON Arrays by using a recursive algorithm.
$myJsonArray = '<as-your-above-json-array>';
# Convert $myJsonArray into an associative array
$myJsonArray = json_decode($myJsonArray, true);
recursiveArray($myJsonArray);
# A recursive function to traverse the $myJsonArray array
function recursiveArray(array $myJsonArray)
{
foreach ($myJsonArray as $key => $hitElement) {
# If there is a element left
if (is_array($hitElement)) {
# call recursive structure to parse the jsonArray
recursiveArray($hitElement);
} else {
if ($key === 'desc') {
echo $hitElement . PHP_EOL;
}
}
}
}
/**
OUTPUT
e1f96b98047adbc39f8baf8f4aa36f41
d0e850f728b2febee79e1e7d1186c126
bee3120e77092d889c3b9e27cbee75bd
32a81cb610805d9255d5f11354177414
88a8e85db11976082fed831c4c83838e
39c4d4bca1578194801f44339998e382
6b4c4d5f4ae609742c1b6e62e16f8650
*/
Live code -> https://wtools.io/php-sandbox/bFEJ
OR use the RecursiveArrayIterator to traverse the $myJsonArray array
$myJsonArray = json_decode($myJsonArray, true);
$myIterator = new RecursiveArrayIterator($myJsonArray);
recursiveArray($myIterator);
function recursiveArray(RecursiveArrayIterator $myIterator)
{
while ($myIterator->valid()) {
if ($myIterator->hasChildren()) {
recursiveArray($myIterator->getChildren());
} else {
if ($myIterator->key() === 'desc') {
echo $myIterator->current() . PHP_EOL;
}
}
$myIterator->next();
}
}
Live code -> https://wtools.io/php-sandbox/bFEL
How I can get text from below JSON.
https://jsfiddle.net/7h6a55m6/2/ JSON Data
Need to get "Testing","Testing2", etc. Stuck in multi level JSON style. Whats the easiest way to do
foreach ($response->data as $res) {
echo $res['comments'];
}
Use the json_decode().Something like below
$test_json='
{ "media":
{ "data":
[
{ "comments":
{ "data":
[
{ "text": "Testing", "id": "17935572247064063" },
{ "text": "Testing2", "id": "17909467621160083" },
{ "text": "Testing3", "id": "17879193508206704" },
{ "text": "Testing4", "id": "17936230114007492" },
{ "text": "Testing5", "id": "17861359981236880" },
{ "text": "Testing6", "id": "17932586956016890" },
{ "text": "Testing7", "id": "17920569544116678" },
{ "text": "Testing8", "id": "17933592700059204" }
]
}
}
]
}
}
';
$test_json=json_decode($test_json,true);
foreach($test_json['media']['data'][0]['comments']['data'] as $row){
print_r($row['text']);
}
try
$responseData = json_decode($response->data, true);
$result = $responseData['media']['data'][0]['comments']['data'];
foreach($result as $data) {
// do your stuff here
}
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);