Extract values from multiple arrays - php

I'm currently using the Adobe Echosign API to format some data in a table. The output looks like this:
{
"agreementId": "",
"events": [
{
"actingUserEmail": "",
"actingUserIpAddress": "",
"date": "date",
"description": "",
"participantEmail": "",
"type": "",
"versionId": ""
}
],
"locale": "",
"modifiable": false,
"name": "",
"nextParticipantSetInfos": [
{
"nextParticipantSetMemberInfos": [
{
"email": "",
"waitingSince": "date"
}
]
}
],
"participantSetInfos": [
{
"participantSetId": "",
"participantSetMemberInfos": [
{
"email": "",
"participantId": ""
}
],
"roles": [
""
],
"status": ""
}
],
"status": "",
"vaultingEnabled": false
}
I'm looping through multiple agreements and this outputs them each as a separate array.
This is probably a really basic question, but how would I go through each array and extract say the 'participantEmail', 'name' and 'status' values?
Thanks!

Depending on what programming language you are using, there are a lot of ways to handle this. In JS you could convert this JSON array into JS Array of Objects and after that you can access them using JS processing.
Example for JS would be:
var input = 'yourJSONstring';
var jsObject = JSON.parse(input);
for(var foo in jsObject){
var name = foo.name;
var participantEmail= foo.events[0].participantEmail;
var status = foo.participantEmail[0].status;
}

Supposing that you have an array of agreements with the format you provided, you could do something like this:
<?php
$json = '[{
"agreementId": "",
"events": [
{
"actingUserEmail": "",
"actingUserIpAddress": "",
"date": "date",
"description": "",
"participantEmail": "an email",
"type": "",
"versionId": ""
}
],
"locale": "",
"modifiable": false,
"name": "a name",
"nextParticipantSetInfos": [
{
"nextParticipantSetMemberInfos": [
{
"email": "",
"waitingSince": "date"
}
]
}
],
"participantSetInfos": [
{
"participantSetId": "",
"participantSetMemberInfos": [
{
"email": "",
"participantId": ""
}
],
"roles": [
""
],
"status": "a status"
}
],
"status": "",
"vaultingEnabled": false
}]';
$parsed = json_decode($json, true);
$names = [];
foreach($parsed as $agreement) {
$names[] = $agreement['name'];
$emails = [];
foreach($agreement['events'] as $event) {
$emails[] = $event['participantEmail'];
}
$status = [];
foreach($agreement['participantSetInfos'] as $participant) {
$status[] = $participant['status'];
}
}
var_dump($names);
var_dump($emails);
var_dump($status);
Of course you should do some checks for empty values and so, but just to give you an idea.
Since you do not clarify the relation between name, status and email, i just took them in separate arrays, but that's nothing that can't be fixed with some array handling.
Hope this helps!

Related

php echo from a start point to a end point

I have built a php site that takes code from a page using GET, and then echos it to the current page, but it exports text like this,
{ "selection13": [ { "name": "L" }, { "name": "100%\nA" } ], "selection7": [ { "name": "S" }, { "name": "100%\nA" } ], "selection8": [ { "name": "SS" }, { "name": "100%\nA" } ], "selection9": [ { "name": "SP" }, { "name": "100%\nA" } ], "selection10": [ { "name": "P" }, { "name": "100%\nA" } ], "selection11": [ { "name": "A" }, { "name": "100.00%\nA+" } ], "selection12": [ { "name": "H", "selection5": [ { "name": "T }, { "name": "100.00%\nA+" } ] }, { "name": "100.00%\nA+", "selection5": [ { "name": "T" }, { "name": "100.00%\nA+" } ] } ] }
I need to organizes it in to categorizes like, {L},{100%), here is the code I am currently using,
<?php
$params = http_build_query(array(
"api_key" => "()",
"format" => "json"
));
$result = file_get_contents(
'(url)'.$params,
false,
stream_context_create(array(
'http' => array(
'method' => 'GET'
)
))
);
echo gzdecode($result);
?>
Your script is outputting JSON but there appears to be a few issues with the data itself that need to be addressed first.
The next to the last "name": "T is missing a closing quote.
Section 12 has an inconsistent organization compared to the other sections. Can a section be a child of another section or is this an error?
"selection11": [
{
"name": "A"
},
{
"name": "100.00%\nA+"
}
],
"selection12": [
{
"name": "H",
"selection5": [
{
"name": "T"
},
{
"name": "100.00%\nA+"
}
]
},
{
"name": "100.00%\nA+",
"selection5": [
{
"name": "T"
},
{
"name": "100.00%\nA+"
}
]
}
]
These 2 issues need to be fixed in the JSON data you are retrieving first.
From there, the best way to reorganize this is to convert it to an array using json_decode.
$json = gzdecode($result);
$resultArray = json_decode($json);
I can't tell from your question exactly how you want to reorganize the data but use one or more of the builtin array functions to get the data in the structure you want. If you need to output it in JSON, use json_encode on the manipulated array to get the final data format. More specific help can be provided if you can be more clear on want output structure you are looking for and the format (does it need to be JSON or something else).

Format the json encode just like on laravel php

Supposed I have a query that gets the image from a certain tweet
[
{
"pic": "/upload/15680712995mb.jpg",
"tweet_id": "48"
},
{
"pic": "/upload/1568071299test.PNG",
"tweet_id": "48"
},
{
"pic": "/upload/1568015310test.PNG",
"tweet_id": "47"
}
]
And I have a result also from a query that gets all of the tweet
[
{
"id": "48",
"tweet": "test",
},
{
"id": "47",
"tweet": "test tweet",
},
{
"id": "45",
"tweet": "test tweet 3",
}
]
How can I format the result like this (Just like on laravel)
[
{
"id": "48",
"tweet": "test",
"pics": [
[
"/upload/15680712995mb.jpg"
],
[
"/upload/1568071299test.PNG"
],
]
},
{
"id": "47",
"tweet": "test tweet",
"pics" : [
[
"/upload/1568015310test.PNG"
]
]
},
{
"id": "45",
"tweet": "test tweet 3",
"pics" : []
}
]
And this is my simplified code
public function getTweets()
{
$pics = $this->model->getPics();
$aTweets = $this->model->getTweets();
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
foreach ($pics as $pic) {
if ($pic['id'] === $sTweet['tweet_id']) {
$map['pics'] = [$pic['pic']];
}
}
$props[] = $map;
}
return $props;
}
but it just gives me the following output
{
"id": "48",
"tweet": "test",
"pics": [
"/upload/1568015310test.PNG"
]
},
{
"id": "47",
"tweet": "test tweet",
"pics": [
"/upload/1568015310test.PNG"
]
},
Any idea how can I format the result. thanks in advance.?
I'm not sure what's troubling you but in order to add multiple values inside, just put another nesting like what I've eluded in the comments section:
$map['pics'][] = $pic['pic'];
// ^
So to complete the answer:
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
$map['pics'] = []; // initialize
foreach ($pics as $pic) {
if ($pic['tweet_id'] === $sTweet['id']) {
$map['pics'][] = [$pic['pic']];
}
}
$props[] = $map;
}
This essentially creates another dimension for pics index as an array and continually pushing, provided they have the same ID.
Sidenote: tweet_id is to pics and id is to aTweets. Your's have the other way around.

PHP. change value in Array of Arrays not working

very weird issue: I try to change a json string using json_encode and json_decode. I converted the json string to an array(actually it's array of arrays) and try to change some data in it. but I couldn't get the data changed in inner array somehow.
$jsondata = ' {
"Id": "0400006",
"LastName": "Lincoln",
"FirstName": "Abraham",
"PreferredName": "Mr. Abraham Lincoln",
"BirthDate": "1992-06-20T00:00:00",
"PreferredEmailAddress": null,
"Addresses": [
{
"AddressId": "297143",
"Type": "Home",
"AddressLines": [
"201 S Grant Ave"
],
"AddressModifier": "",
"City": "Columbus",
"State": "OH",
"PostalCode": "43215",
"County": "049",
"Country": "",
"RouteCode": "",
"PhoneNumbers": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressLabel": [
"201 S Grant Ave",
"Columbus, OH 43215"
],
"PersonId": "0400006",
"EffectiveStartDate": "2008-06-13T00:00:00",
"EffectiveEndDate": null,
"IsPreferredAddress": true,
"IsPreferredResidence": true,
"TypeCode": "H",
"CountryCode": ""
},
{
"AddressId": "727032",
"Type": "Web Address",
"AddressLines": [
"285 E. Main Ave",
"Apt B"
],
"AddressModifier": "",
"City": "Columbus",
"State": "OH",
"PostalCode": "43215",
"County": "049",
"Country": "",
"RouteCode": "",
"PhoneNumbers": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressLabel": [
"285 E. Main Ave",
"Apt B",
"Columbus, OH 43215"
],
"PersonId": "0400006",
"EffectiveStartDate": "2018-06-25T00:00:00",
"EffectiveEndDate": null,
"IsPreferredAddress": false,
"IsPreferredResidence": false,
"TypeCode": "WEB",
"CountryCode": ""
}
],
"EmailAddresses": [],
"Phones": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressConfirmationDateTime": null,
"EmailAddressConfirmationDateTime": null,
"PhoneConfirmationDateTime": null,
"LastChangedDateTime": "2018-06-27T20:42:22Z",
"ChosenFirstName": "",
"ChosenMiddleName": "",
"ChosenLastName": "",
"PersonalPronounCode": "",
"IsDeceased": false
}
';
$newAddressData = [
"address1" => "5857 Newbridge Dr.",
"address2" => "Apt D",
"city" => "Chicago",
"state" => "Illions",
"postalcode" => "23456"
];
public function modifyData($jsonStr, $newAddressData){
$personInfoData = json_decode($jsonStr, true);
$addressArray = $personInfoData['Addresses'];
$webAddressObj = null;
foreach($addressArray as $address){
if($address['Type'] == 'Web Address' ){
$webAddressObj = &$address;
break;
}
}
if($webAddressObj != null){
echo("update it!");
$webAddressObj['AddressId'] ='';
$webAddressObj['PhoneNumbers']=[];
$webAddressObj['AddressLabel'] =[];
$webAddressObj['AddressLines'] =[$newAddressData['address1'], $newAddressData['address2']];
$webAddressObj['EffectiveStartDate']='';//2018-06-25T00:00:00
$webAddressObj['City']=$newAddressData['city'];
$webAddressObj['State']=$newAddressData['state'];
$webAddressObj['PostalCode']=$newAddressData['postalcode'];
}else{
echo("new address");
$newAddress = new AddressInfo();
$newAddress->Type = "Web Address";
$newAddress->TypeCode = "WEB";
$newAddress->AddressLines =[$newAddressData['address1'], $newAddressData['address2']];
$newAddress->EffectiveStartDate ='';
$newAddress->City = $newAddressData['city'];
$newAddress->State=$newAddressData['state'];
$newAddress->PostalCode=$newAddressData['postalcode'];
$newAddressJson = json_encode($newAddress);
$addressArray[] = $newAddressJson;
}
print_r($webAddressObj);
echo "<p>";
print_r($addressArray);
echo "<p>";
return $personInfoData;
}
$personalInfoData = modifyData($jsondata, $newAddressData);
echo json_encode($personalInfoData);
========================================
You'll find out the $personalInfoData didn't get changed.
This: $webAddressObj = &$address; does not create a reference to that element of the original array. It creates a reference to the temporary copy of the element created by foreach. The reference to that copy does stay set after you've broken out of the loop, but making changes to it will not affect the original array.
If you want a reference to the original element, You'll also need to assign $addressArray by reference to begin with.
$addressArray = &$personInfoData['Addresses'];
you'll need to maintain the reference in the foreach loop, like
foreach($addressArray as &$address){
And you'll still need to assign by reference inside the loop as you're currently doing.
$webAddressObj = &$address;
Rather than keeping track of all the references, it may be easier to follow if you refer directly to the original array by key instead.
$webAddressKey = null;
foreach($addressArray as $key => $address){
if($address['Type'] == 'Web Address' ){
$webAddressKey = $key;
break;
}
}
if($webAddressKey != null){
echo("update it!");
$personInfoData['Addresses'][$webAddressKey]['AddressId'] ='';
...
}

PHP How to get a particular JSON values/parameter

This is my JSON Response came from an URL API. I use GuzzleHttp\Client and json_decode() inorder to manage.
[{
"INDEX_ID": "0",
"NOTES": "0; Farming"
},
{
"INDEX_ID": "1",
"NOTES": "Fruit Name; List of Fruits;"
},
{
"INDEX_ID": "2",
"NOTES": "Apple"
},
{
"INDEX_ID": "3",
"NOTES": "Orange"
},
{
"INDEX_ID": "4",
"NOTES": "Grapes"
},
{
"INDEX_ID": "5",
"NOTES": "Mango"
},
{
"INDEX_ID": "6",
"NOTES": "Animal Name; List of Animal;"
},
{
"INDEX_ID": "7",
"NOTES": "Pig"
},
{
"INDEX_ID": "8",
"NOTES": "Goat"
},
{
"INDEX_ID": "9",
"NOTES": "Cow"
}]
But I only need to save list of Fruits in my logfile. Can someone help me how to exclude the other json parameters and get only the particular json parameters using foreach loop or any method inorder to get that result.
I just want it to be like this:
[
{
"NOTE_NO." : "001",
"CATEGORY" : "FRUITS",
"LISTS_TO_BUY" : [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
He're my codes so far:
$response_body = json_decode($json_response, true);
$json_new_param = [];
foreach ($response_body as $value) {
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
$header = [
[
'NOTE_NO.' => '001',
'CATEGORY' => 'FRUITS',
'LISTS_TO_BUY' => $json_new_param
]
];
echo json_encode($header);
$json_response is the response given above.
You might use array_reduce to return an array where the key will be the first word from the value using implode which has this structure: "NOTES": "Fruit Name; List of Fruits;". The key for this would then be "Fruits".
During the array_reduce keep track of the current key using a variable $currKey
At the end you could then get the data by using "FRUIT" (Which is the first word) as the array key: $response_body["FRUIT"]
$response_body = json_decode($json_response, true);
$currKey = "0";
$response_body = array_reduce($response_body, function ($carry, $item) use (&$currKey){
if (strpos($item['NOTES'], 'Name; List') !== false) {
$currKey = strtoupper(explode(" ", $item["NOTES"], 2)[0]);
return $carry;
}
$carry[$currKey][] = ["FRUITS" => $item["NOTES"]];
return $carry;
});
$result = [
[
"NOTE_NO" => "001",
"CATEGORY" => ($name = "FRUITS"),
"LISTS_TO_BUY" => $response_body["FRUIT"]
]
];
echo json_encode($result, JSON_PRETTY_PRINT);
That will result in:
[
{
"NOTE_NO": "001",
"CATEGORY": "FRUITS",
"LISTS_TO_BUY": [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
Demo
Try this code .
$json_new_param = [];
$fruitFlag = false;
foreach ($response_body as $value) {
if(strpos($value['NOTES'],'Fruit Name') !== false){
$fruitFlag = true;
continue;
}
if(strpos($value['NOTES'],'Animal Name') !== false){
$fruitFlag = false;
}
if($fruitFlag == true){
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
}
echo json_encode($json_new_param, JSON_PRETTY_PRINT);

Build Json from database with php

I've written a simple PHP file, which pull my Data from the Database and return it with $row["fieldname"]. So now i need to know how i return is as json like below.
Normally i would start it with creating a array
$arr = [
'Name' => $row["_LSMOUSER"],
'Pass' => $row["_LSMOPASSWORT"] ];
And would encode it with
json_encode($arr, JSON_PRETTY_PRINT);
But, how i can add the Points "Rights, Masks & Key like below?
{
"Users": [
{
"Name": "user",
"Pass": "passwort",
"Rights": {
"Masks": [
{ "Key": "FAQ", "Access": true },
{ "Key": "Hilfebereich", "Access": false }
]
}
},
{
"Name": "user2",
"Pass": "passwort2",
"Rights": {
"Masks": [
{ "Key": "FAQ", "Access": true },
{ "Key": "Hilfebereich", "Access": true }
]
}
}
]
}
Something like this:
$arr = array(
'Name' => $row["_LSMOUSER"],
'Pass' => $row["_LSMOPASSWORT"],
'Rights'=>array(
'Masks'=>array( array('Key'=>'FAQ', 'Access'=>true),
array('Key'=>'Hilfebereich', 'Access'=>false)
)
)
);
// OutPut
"Name": "user",
"Pass": "passwort",
"Rights": {
"Masks": [
{ "Key": "FAQ", "Access": true },
{ "Key": "Hilfebereich", "Access": false }
]
}
then json_encode($arr)

Categories