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).
Related
I tried to replace a json value if the id from json1 same with json2 than replace the name in json1, here my json:
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"10","name":"Blog"},{"categoryId":"11","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
My expected result is:
$json1 = '[{"categoryId":"10","name":"Tech"},{"categoryId":"10","name":"Tech"},{"categoryId":"11","name":"Programming"}]';
I did with javascript so far:
json1.forEach(function(json1) {
if (json2.categoryId === json1.categoryId) {
json1.name = json2.name
}
});
but how to do it over php language?
This will help you I hope
// Your json data
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"11","name":"Blog"},{"categoryId":"12","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
// Turn json into an array
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// Loop to json2 as array
foreach ($array2 as $value) {
$categoryId = $value['categoryId'];
// Check if the categoryId exist in array 1 and get the index key
$key = array_search($categoryId, array_column($array1, 'categoryId'));
// Check if the key exist ena check if it has a name to be changed
if (isset($array1[$key]) && isset($array1[$key]['name'])) {
// Set the new name
$array1[$key]['name'] = $value['name'];
}
}
// Turn the array back into json
$json1 = json_encode($array1);
Did your solution work in JS? It seems to me, that in the loop, you should be comparing with the first entry of the json2 variable, as the whole json2 is a list of objects and does not itself have a name property.
In PHP, this could work like this:
$arr1 = json_decode($json1);
$arr2 = json_decode($json2);
$arr2entry = $arr2[0]; # this is what we want to compare against
foreach ($arr1 as &$arr1entry) { #[1]
if ($arr2entry["categoryId"] == $arr1entry["categoryId"]) {
$arr1entry["name"] = $arr2entry["name"];
}
}
#[1] notice the ampersand here, that's a reference assignment,
#it is needed to actually modify the content of the original array.
I'm using below logic to store data in JSON format in MySQL using PHP.
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
session_start();
$date = new Date();
$modified = $date->getDate();
$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';
Then while decoding the data i'm using below logic:
$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$var = html_entity_decode($row['data']);
echo json_decode($var);
}
}
While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output
{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}
I'm not sure where i'm going wrong, could anybody help me out here?
I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so
echo json_encode(
array(
"type" => "error",
"status" => "Error While Retrieving Data!",
"message" => $error
)
);
I think you need something like:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[] = array($value[1] => $value[2]);
else
$store[] = array($value[1] => trim($value[2]));
}
$save = json_encode($store);
or even (if your $value[1] is always unique within the loop)
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
$save = json_encode($store);
then use $save to store in your table. I'm not 100% on that, though.
The string you've shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.
Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:
$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$storedata[] = array($value[1] => $value[2]);
else
$storedata[] = array($value[1] => trim($value[2]));
}
$jsondata = json_encode($storedata);
And then use $jsondata in your SQL statement.
Your problem is your "saving" to the database. You encode every key-value-pair in an own json-string and concat those json-strings.
Your snippet
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.
However, I assume you want a single json-object with the key-value-pairs as result like the folling?
$store = "{
key1:value1,
key2:value2,
key3:value3
}";
If so, you need to build your array differently:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.
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']
}
So I am trying to make, code will get certain parts matching ID's from the JSON array.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, true);
//-------------------------------------
$invIndexes = [];
foreach($json->rgInventory as $index){
$invIndexes = $index;
}
//-------------------------------------
$makearray = (array)$invIndexes;
for($id = 0;$id < count($invIndexes);$id++){
$index = $makearray[$id];
$item = $json->rgDescriptions[$json->rgInventory[$index]->classid + "_" + $json->rgInventory[$index]->instanceid];
if($item->tradeable != 1){
continue;
}
$ItemName = $item->market_hash_name;
}
var_dump($ItemName);
Here's the JSON: http://pastebin.ca/3591035
The $ItemName return's NULL but it shouldn't (At least I think that). Maybe someone can spot the mistake what I've been doing here :/
If you are you using true in json decode $json = json_decode($response, true);, then it will return an associative array, so you can access the value form array simply like this $json['rgInventory'] not $json->rgInventory
To create $invIndexes array use this:
$invIndexes = array();
foreach($json['rgInventory'] as $index){
$invIndexes[] = $index['id'];
}
Here you will get $invIndexes the in your for loo you are again using $json->rgDescriptions to access values, change this to $json['rgInventory'] and for all other values use array keys like this $json['rgInventory']['index']['class']
No need of this $makearray = (array)$invIndexes; directly use $invIndexes
$index = $invIndexes[$id];
$item = $json['rgDescriptions'][$json['rgInventory'][$index]['classid']."_".$json['rgInventory'][$index]['instanceid']];
Another mistake is that in your $item there is not any key tradeable, its tradable an use like this
if($item['tradeable'] != 1){
continue;
}
$ItemName = $item['market_hash_name'];
At last var_dump($ItemName);
The second argument true to json_decode tells it to convert JSON objects into PHP associative arrays rather than PHP objects. But using syntax like $json->rgDescriptions requires $json to be an object; for an array it should be $json['rgDescriptions'].
So either change all your uses of $json to use array syntax, or remove the true argument from json_decode. The latter should be easier.
Also, this line:
$invIndexes = $index;
should be:
$invIndexes[] = $index;
But you could replace that loop with just:
$invIndexes = $json->rgInventory;
I'm trying to filter an array (derived from a json object), so as to return the array key based on the value. I'm not sure if array search $key = array_search($value, $array); is the best way to do this (I can't make it work), and I think there must be a better way.
So far I've got this, but it isn't working. Grateful for any help!
public function getBedroomData(array $data,$num_beds = null,$type) {
$data = (array) $data;
if($num_beds > 0) {
$searchstring = "avg_".$num_beds."bed_property_".$type."_monthly";
} else {
$searchstring = "avg_property_".$type."_monthly";
}
$avg_string = array_search($data, $searchstring);
return $avg_string;
}
The array consists of average property prices taken from the nestoria api as follows:
http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json
This returns a long json object. My problem is that the data isn't consistent - and I'm looking for the quickest (run time) way to do the following:
$data['response']['metadata']['0'] //= data to return, [0] unknown
$data['response']['metadata']['0']['metadata_name'] = "avg_1bed_property_rent_monthly" //= string I know!
$data['response']['metadata']['1'] //= data to return, [1] unknown
$data['response']['metadata']['1']['metadata_name'] = "avg_1bed_property_buy_monthly" //= string I know!
$data['response']['metadata']['2'] = //= data to return, [2] unknown
$data['response']['metadata']['2']['metadata_name'] = "avg_2bed_property_buy_monthly" //= string I know!
.....
.....
.....
$data['response']['metadata']['10'] = avg_property_rent_monthly
$data['response']['metadata']['11'] = avg_property_buy_monthly
$data['response']['metadata'][most_recent_month] = the month reference for getting the data from each metadata list..
It isn't possible to filter the initial search query by number of bedrooms as far as I can work out. So, I've just been array slicing the output to get the information I've needed if bedrooms are selected, but as the data isn't consistent this often fails.
To search inside that particular json response from nestoria, a simple foreach loop can be used. First off, of course call the json data that you need. Then, extract the whole data, the the next step if pretty straightforward. Consider this example:
$url = 'http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
$metadata = $data['response']['metadata'];
// dummy values
$num_beds = 1; // null or 0 or greater than 0
$type = 'buy'; // buy or rent
function getBedroomData($metadata, $num_beds = null, $type) {
$data = array();
$searchstring = (!$num_beds) ? "avg_property_".$type."_monthly" : "avg_".$num_beds."bed_property_".$type."_monthly";
$data['metadata_name'] = $searchstring;
$data['data'] = null;
foreach($metadata as $key => $value) {
if($value['metadata_name'] == $searchstring) {
$raw_data = $value['data']; // main data
// average price and data points
$avg_price = 0;
$data_points = 0;
foreach($raw_data as $index => $element) {
$avg_price += $element['avg_price'];
$data_points += $element['datapoints'];
}
$data_count = count($raw_data);
$price_average = $avg_price / $data_count;
$data_points_average = $data_points / $data_count;
$data['data'][] = array(
'average_price' => $price_average,
'average_datapoints' => $data_points_average,
'data' => $raw_data,
);
}
}
return $data;
}
$final = getBedroomData($metadata, $num_beds, $type);
print_r($final);