update json replacing variable input from form in php - php

Greeting, I'm new to PHP, and currently looking for a way to edit json.
I have a form to input the key that wants to edit. I echo the input from form and successfully got the output showing but it didn't pass to json file to update. The code is as below.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
//you this post contain test?
//test is the the button when i submit the form
if (array_key_exists('test',$_POST))
{
testfun();
}
Am I missing something?

Try my code.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = array(json_decode($data, true));
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
if (array_key_exists('test',$_POST))
{
testfun();
}

As you mention in the comments, the content of the $json_arr is:
{"CELL_NAME":"1234A","#25":"remark value"}
So when you trying to access in:
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
it has no key for $value at CELL_NAME key.
I guess your $data from the file should be like that (an array of JSONs):
$data = '[{"CELL_NAME":"1234A","#25":"remark value"}, {"CELL_NAME":"1234B","#25":"remark value"}]';
Now you can do this and it will work:
$arr = json_decode($data, true);
foreach ($arr as $key => $value) {
if ($value['CELL_NAME'] == "1234A") // you can change with $_POST['in_cell']
$arr[$key]['#25'] = "test"; // you can change with $_POST['in_remark']
}

Related

How to create a dynamic JSON array in PHP using multiple for eaches?

I need to generate a JSON Object and push it to a JSON object array using PHP.
This is my code.
public function getJSONData()
{
$csv = $this->getCsvData();
$finalArray = array();
// First foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Second foreach to iterate the headlines array.
$newArray = array();
foreach ($csv["headlines"] as $index => $headline) {
// $newArray[$key]->$csv["headlines"] = $value;
// print_r($headline);
// print_r($value[$index]);
// echo " ";
array_push($newArray, array($headline => $value[$index]));
}
echo json_encode($newArray);
echo "<br>";
array_push($finalArray, json_encode($newArray));
}
// dd($finalArray);
}
From this code, I'm getting the following response.
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
But it is not a valid JSON and I really need to get an output like this:
[{"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":639.95}, {"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":509.95}]
This is a standard JSON object array.
In my code, I'm using array_push($newArray, array($headline => $value[$index])); to generate the array and take it as JSON.
Please help me on this.
You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...
// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);
}
echo json_encode($finalArray);

Need Proper JSON

I need to show data in Attribute and Value form but data is getting is in direct form.
I am trying this
Getting Data in this FOrm
{"FirstName":"sbncf","EmailAddress":"jscn#jnsc.cs","LastName":"jj","Phone":"653736","SearchBy":"jhjnjn"}
But i need in this Form
$data_string = '[{"Attribute":"FirstName","Value":"Bret"},{"Attribute":"LastName","Value":"Lee"},{"Attribute":"EmailAddress","Value":"bret.lee#australia.com"},{"Attribute":"Phone","Value":"8888888888"},{"Attribute":"SearchBy","Value":"Phone"}]';
I am using AJAx and using this
$data_string = json_decode(json_encode($_POST));
enter image description here
You need to store data into an another array, new array must contains Attribute and Value indexes, something like this example:
// testing $_POST data
$post = array();
$post['FirstName'] = 'sbncf';
$post['EmailAddress'] = 'jscn#jnsc.cs';
$post['LastName'] = 'jj';
$newArray = array(); // initialize new array
$i = 0;
foreach ($post as $key => $value) {
$newArray[$i]['Attribute'] = $key;
$newArray[$i]['Value'] = $value;
$i++;
}
//use json_encode here:
$data_string = json_encode($newArray);
echo $data_string;
Result:
[{"Attribute":"FirstName","Value":"sbncf"},{"Attribute":"EmailAddress","Value":"jscn#jnsc.cs"},{"Attribute":"LastName","Value":"jj"}]

How to prevent overriding in array?

I'm trying to add all the keys of different json available in a file to an array. What I did for the moment is this:
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
//Iterate through the json keys
foreach($array as $k => $val)
{
$json[$k] = $val;
}
}
the json file is like this:
{"Timestamp":"2018-06-14T10:46:52.3326036+02:00","Level":"Error","MessageTemplate":"System.Exception"}
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
I'll get this:
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
because the $json[$k] override I guess the previous array, but $k is a new json so why the index of the array is replaced?
Thanks in advance for any help.
may be this one is your expected output.
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
$temp = [];
//Iterate through the json keys
foreach($array as $k => $val)
{
$temp[$k] = $val;
}
$json[] = $temp;
}
change this line
foreach($array as $k => $val)
{
$json[$k] = $val;
}
to
foreach($array as $k => $val)
{
$json[][$k] = $val;
}
Well you're overwriting keys with the same names, so there's really nothing surprising in your output.
You probably meant to do this:
foreach($jsonData as $line) {
$tmp = []; //<-- set up a new array just for this iteration
$array = json_decode($line, true);
foreach($array as $k => $val) $tmp[$k] = $val;
$json[] = $tmp; //<-- log the array in the master $json array
}
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Convert the json in an associative array
$array = json_decode($jsonData, true);
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($array as $k => $val)
{
$json[][$k] = $val;
}

Parse JSON data from multiple options

I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13

Can't change value in json

I have a .json file with player name, mail address, field name and score on that field. Like this:
{"0":{"name":"test","password":"test","mail":"test#test.test","test3":0,"test2":0},"1":{"...
I want to change the score at one field, but I can't. I tried this way:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
$arrayy[$felhasznev][$palya] = $pontszam;
And I also tried this but not helped:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
foreach ($arrayy as $key => $valuee){
if($valuee['name'] == $username){
$valuee[$field] = $score;
}
}
I'm beginner in JSON so maybe something trivial...
Function json_decode parse json file to objects, you're using associative array, to have an associative array you have to pass a second argument as true, like:
<?php
$file = file_get_contents("file.json");
$players = json_decode($file, true);
$err = json_last_error();
if ($err != JSON_ERROR_NONE) {
print_r($err);
die("Error in json file :/");
}
var_dump($players);
foreach ($players as $key => $val) {
if ($players[$key]["name"] == "test") {
$players[$key]["test3"] = $players[$key]["test3"] + 1;
$players[$key]["test2"] = $players[$key]["test2"] + 1;
}
}
var_dump($players);
file_put_contents("new_file.json", json_encode($players));
(1) In your sample json, there is value (0) not enclosed in double quote (parsing error!).
(2) the first code should work if json is ok.
(3) in the second code, you skipped the "id" identifier (if json is ok).

Categories