Removing the specific json data displayed from for loop in php - php

I have a json file with some data that I'm displaying on my website using php foreach.
I need 2 functions for that:
Add new element (which I coded without any troubles)
Remove specific data (which I'm struggling with)
The question is - I dont know how to pass an selected element ID, because $_POST takes the input's name key, and I cant pass it to function dynamically.
Here is my code that displays data in html:
$index = 0;
foreach (json_decode($data) as $element) {
$isDone = $element->isDone ? '+' : '-';
echo $isDone ." ". $element->name . "<br>";
echo "<form action='/operateJson.php'>";
echo "<input type='submit' value='-' style='background-color: red;' name='remove$index'>";
echo "</form>";
$index++;
}
And it looks like that
Here is my code from action
function addRow($row, $rowname): void
{
$jsonData = file_get_contents($row);
$data = json_decode($jsonData, true);
$data[strval(count($data))] = array(
'name' => strval($rowname),
'isDone' => 0
);
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents('../db.json', $jsonData);
}
if (isset($_POST["1"])) {
addRow("../db.json", $_POST["rownamefirst"]);
}
That is working, but I need to add a function that executes after clicking the red button and then removing the chosen element from json

Related

Trying to add totals for each employee with data that is stored in array in PHP

So I am trying to write a script where I have obtained data that has employee names and the amounts they are paid from a database. The information was retrieved in JSON format, which I think I decoded correctly and put into an associative array. The problem I am running into is figuring out how to loop through the array to obtain the total paid for each employee.
Here is my code so far starting at the section where I decoded the JSON file.
//decode JSON file
$payout_array = json_decode($info, true);
echo '<pre>' . print_r($payout_array, true) . '</pre>';
/*foreach($payout_array as $key=>$value)
{
if($key['Name'] == "Jane")
{
$jane_payout = array_sum($value['Amount']);
}
if($name == "Mark")
{
$mark_payout = sum($amount);
}
}*/
/*foreach ($payout_array as $key => $sub_array) {
foreach ($sub_array as $sub_key => $value) {
if($value['Name'] == "Jane")
{
$jane_payout = array_sum($value['Amount']);
}
if($value == "Mark")
{
$mark_payout =+ sum($value['Amount']);
}
}
}*/
//Proccess data to calculate the amount paid to each employee
/*$mark_payout = array_sum($payout_array->Amount);*/
echo "Jane $".number_format($jane_payout, 2);
echo "<br>";
echo "Mark $".number_format($mark_payout, 2);
?>
The result I am currently seeing in the browser is
first section of array
second section of array
errors and total
On picture three you can see Jane and Mark show a total for $0.00. My goal is to have the $0.00 actually display the total that was paid to each employee from all the array entries. Once I am able to do that I will be encoding that new information into a JSON file and posting it to a client server. The end result that the client needs to see is the name of the employee and the total amount they have been paid.
I have tried various foreach loops and even left some commented out in the code but can't get it to access the elements correctly to perform the calculations. I am new to this and have very little experience with PHP so any help is very much appreciated!
Untested but this is generally what you're looking for.
<?php
$payout_array = json_decode($info, true);
echo '<pre>' . print_r($payout_array, true) . '</pre><br/><br/><br/><br/>';
foreach($payout_array['records'] as $key => $value)
{
if (!array_key_exists('fields', $value)) {
print 'Bad input data detected' . PHP_EOL;
}
$name = $value['fields']['Name'] ?? 'no name given';
$payout_array[] = [
'name' => $name,
'total_payout' => $total = $value['fields']['Amount'] ?? '0'
];
print $value['Name'] . ' $' . number_format($total, 2) . '<br/>';
}

Display Php (json) output in tabular format

I am new to Wordpress Plugin Developement,Wrote a function that requests a url for data and gets the same in Json Format,The Function Snippet is as follows;
function user_det()
{
$em = '';
$url = ''.$em;
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
echo '<pre>' , print_r($myhtml) , '</pre>';
}
The Output:
{
"Status":"Success",
"Bookings":[
{
"Message":"",
"Detail":{
"ServiceType":"",
"HoName":"",
"HAddress1":"",
"ToRooms":"",
"RoDetail":[
{
"RoomTypeDescription":[
" "
],
"NumberOfRooms":"",
"Passengers":[
{
"Salutations":"",
"FirstName":"",
"LastName":""
},
{
"Salutations":"",
"Age":"",
"CotBedOption":""
}
],
"totalAdult":2,
"totalChild":0
}
],
"Phone":"-",
"Rating":"",
"email":""
}
}]}
However ,Is there a way where I could Display the data in a tabular format,tried searching online but could not understand
As you are getting the information in JSON format from your API request, you'll need to iterate each element to format the way you want, example of building a table using this information.
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
$dataArray = json_decode($myhtml,1);
echo '<table>';
echo '<thead><tr><th>Service Type</th></tr></thead>';
echo '<tbody>';
// Now we have the json converted into an array, let's iterate it
foreach($dataArray["Bookings"] as $idx=>$bookingData) {
// Iterate all bookings and write on the rows
echo '<tr>';
echo '<td>'.$bookingData['Detail']['ServiceType'].'</td>';
echo '</tr>';
}
echo '</tbody><table>';
I believe this gives you the idea on what you need to perform to get your object and build a table.

Add +1 number to an array

session_start();
echo "<form method='post'>";
echo "<input type='text' name='random' placeholder='Product' >";
echo "<input type='submit' value='submit' name='submit'>";
echo "</form>";
if(!$_SESSION['list']) {
$_SESSION['list'] = array(); // create session
}
if(isset($_POST['submit']) && empty($_POST['random'])) { // Check if input is empty
echo "* Input is empty!";
} elseif(isset($_POST['submit']) && isset($_POST['random'])) {
$_SESSION['list'][] += 1; // add +1 to array
}
foreach ($_SESSION['list'] as $value) {
echo $value . "<br>"; // shows the list/array
}
So I tried to make array that add +1 number on a submit, but my array keeps being 1, so it doesn't go like: 1,2,3,4,5... but it goes like: 1,1,1,1,1,1 . They don't add up. How do I fix this?
Given an array $arr, or $_SESSION['list'] in your case, it is possible to append an element to the end of the array as follows.
$arr[] = 'new element';
You try to combine this with the += operator. This will first append 0 to the array and then increment it, resulting in 1 being appended all the time.
It looks like what you actually want to do is this:
$arr[] = end($arr) + 1;
That is, take the last value of the array, add 1 to it and append that to the array.

compare foreach value to $_POST in php

I'm populating select box with options from json file and trying to set value from $_POST as selected. I get all the values printed as options but none selected.
Seems like something goes wrong when comparing $marke to $post so nothing get selected.
<select name="marke" id="marke"class="form-control">
<?php
$url = 'includes/lists/models.json';
$jsonData = file_get_contents($url);
$jsonDataObject = json_decode($jsonData, true);
$post = $_POST['marke'];
$i = 0;
echo '<option>--</option>';
foreach ($jsonDataObject['markes'] as $marke) {
if ($marke==$post) {
echo '<option selected value="'.$marke['title'].'" id="'.$i.'">'.$marke['title'].'</option>';
}else{
echo '<option value="'.$marke['title'].'" id="'.$i.'">'.$marke['title'].'</option>';
}
$i++;
}
?>
</select>
P.S $_POST['marke'] is set correcly.
As I understand it $marke is an array, and most likely $_POST['marke'] is a string or int.
if ($marke['title']==$post) {
instead of
// You'd be comparing a $marke array with $_POST['marke'] string
if ($marke==$post) {

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

Categories