I'm processed some JSON data that is sent via HTTP POST to my PHP file. I then need to extract some elements and create a PHP array containing these, so I can then loop through this array and perform some actions.
Here's a sample of how the JSON data that is sent looks:
[
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server1.acme.com",
"timestamp": 1574229999
},
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server2.acme.com",
"timestamp": 1574228341
},
{
"fileName": "Payments",
"event": "processed",
"hostname": "server3.acme.com",
"timestamp": 1574766997
}
]
I'm then decoding this to parse out just the elements I need:
$payload = #file_get_contents('php://input');
$records= json_decode( $payload, FALSE );
$sessionsArray = array();
foreach($records as $record){
$hostname = $record->hostname;
$fileName = $record->fileName;
// need to add these to the $sessionsArray for each iteration of the loop
}
I would like to create a new array $sessionsArray and add the $hostname and $fileName variables to this for each iteration in the foreach loop. I then intend to do another foreach on the $sessionsArray and perform some actions using the $hostname and $fileName for each element of the array.
I'm stuck on how to add the variables within the first foreach loop to the $sessionsArray array so I can then subsequently loop through that array.
foreach($records as $record){
$sessionsArray[] = [
'hostname' => $record->hostname,
'fileName' => $record->fileName,
];
}
And then you can do:
foreach($sessionsArray as $entry){
$hostname = $entry['hostname'];
$fileName = $entry['fileName'];
}
=== OR ===
foreach($records as $record){
$sessionsArray[$record->hostname] = $record->fileName;
}
and then you can do:
foreach($sessionsArray as $hostname => $fileName){
// $hostname contains the hostname
// $filename contains filename
}
Just FYI, based on the JSON object you provided your code SHOULD be:
$hostname = $record->serverName;
$fileName = $record->fileName;
$sessionsArray = array();
foreach($records as $key => $record){
$sessionsArray[$key]['hostname'] = $record->hostname;
$sessionsArray[$key]['fileName'] = $record->fileName;
}
You need to get the last key of sessionsArray before every loop and pass that last key while adding to variable.
Here is example:
$sessionsArray = !empty($sessionsArray)?$sessionsArray:[];
$continueKey = (#array_pop(array_keys($sessionsArray)))?#array_pop(array_keys($sessionsArray))+1:0;
foreach($records as $record){
$sessionsArray[$continueKey]['hostname'] = $record->hostname;
$sessionsArray[$continueKey]['fileName'] = $record->fileName;
}
Related
I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
So i tried a lot of possible codes out but i can't seem to find a proper solution.
First let's start with the the wished array (i will show it in a json format as it's easier to read)
{
"transaction": {
"input": [
{
"address": "a",
"value": 4294967295
},
{
"address": "b",
"value": 51515
}
],
"output": [
{
"address": "aa",
"value": 551
},
{
"address": "bb",
"value": 66564
}
]
}
}
I'm using 2 foreach loops to get data that i wanna put in inputs & outputs
Here's the code im using:
//Get Output Addresses & Value
$tmp_array = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$input = array_merge($input, $tmp_array);
};
$input = array('inputs' => $tmp_array);
$input = json_encode($input);
print_r($input);
That's the code for me getting the data and trying to put it into the array. Now i have a problem, it only adds data from the last iteration of the loop. I'm trying to get a code that gets it in a strucuture like above. Whatever solution gets sent, it should be applicable so i can paste the same code in the other loop that is for the outputs
You are assigning the $input variable after the loop with the value of $tmp_array which will be the value from the last iteration, as you described. To fix this you should initialize the $input array as empty array at the beginning and merge that with the new data:
//Get Output Addresses & Value
$inputs = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$inputs[] = $tmp_array; // push to array
};
$input = json_encode(array('inputs' => $inputs));
print_r($input);
I'm working with some JSON data like this:
{
"attachments": [
{
"content": "<base 64 encoded attachment>",
"content_type": "image/jpeg",
"original_name": "image000000.jpg"
},
{
"content": "<base 64 encoded attachment>",
"content_type": "image/gif",
"original_name": "gif0001.jpg"
}
],
"source_number": "++614567890"
}
I need to loop through all the attachments array. I can get individual elements like this:
$arr = json_decode($jsonobj, true);
echo $arr[attachments][0]["content_type"]; // returns image/jpeg
but I can't work out the syntax to loop through all of the attachments array and retrieve the values for each of these, something like this pseudo code:
foreach($arr[attachments] as $key => $value) {
$contentType = $arr[attachments][0]["content_type" ;
$content = $arr[attachments][0]["content" ;
$originalName = $arr[attachments][0]["original_name" ;
}
that will generate a variable in the loop for each item in the attachments array.
You don't need the $key, you just need the $value. In the loop, $value is associative array that has the keys content, content_type and original_name:
foreach($arr["attachments"] as $value) {
$contentType = $value["content_type"];
$content = $value["content"];
$originalName = $value["original_name"];
}
You are almost there: $value['content_type'] (and so on) inside your loop will do the trick. (The $key is superfluous.)
Oh and you should use $arr['attachments'] instead of $arr[attachments] probably.
I have a json file with the following syntax:
[
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "asd23f",
"status": "Active",
"perCode": "1",
"idCode": "0987",
"nextCode": "09"
},
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "789096",
"status": "Active",
"perCode": "1",
"idCode": "076543",
"nextCode": "09"
}
]
I would like to use a for loop in order to add something like a userID before or after the nextCode. Is there any solution to this?
So far, I tried this:
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $key=>$c)
{
if (is_array($c))
continue;
$data .= $data . "user_id:$userId";
}
}
Of course it does not make the trick, any ideas please?
There are a few problems.
First, the foreach loop works with a copy of the array it's iterating, so modifying one of the items there won't change the original array.
Then, your inner foreach loop is overwriting the $key from the outer loop. That would cause problems, but it's okay, because you don't actually need the inner loop.
Finally, after you've decoded the JSON string, $data will be an array, so appending to it with .= won't work, and even if it did, you'd just be sticking something on the end of it rather than at the specific point where your loop is.
Just refer to the specific key you need and set the value there.
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
$data[$key]['user_id'] = $userId;
}
$data = json_encode($data);
Another way which is slightly shorter is pass the value by reference &:
$data = json_decode($file, true);
foreach ($data as &$val) {
$val['user_id'] = $userId;
}
https://3v4l.org/ZF4Ve
This is how you can add an element to a parsed JSON and recostruct it back into a JSON:
// parse the JSON into an array
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
// add the userID to each element of the main array
// it will be inserted after the last element (after nextCode)
$data[$key]['userID'] = 'some-id';
}
// if needed, parse the array back to JSON
$data = json_encode($data);
I explain to you
The following expression converts the information from string to array
$data = json_decode ($file, true);
So in your foreach you only have to add the key
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $k=>$c)
{
if (is_array($c))
continue;
$data[$k]['user_id'] = $userId;
}
}
I see everybody answered for array options. I don't see why not using object, though.
I would do it like this:
$data = json_decode($file);
foreach ($data as &$field)
{
$field->userID = $userId;
}
$data = json_encode($data);
I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);