How to unset data from json file - javascript

how do i delete my data in json file, heres my json file data, i want to clear the data of my json file.
{"name":null,"timestart":"00:00","timeend":"00:00","day":null},
{"name":"henrix","timestart":"7:00","timeend":"7:30","day":"tuesday"}]
i tried this code but its not delete the data, its saving another data but its null
<?php
$file = 'timetable.json';
$json_file = file_get_contents($file);
$file_content = json_decode($json_file);
foreach ($file_content as $key => $value) {
$name = $file_content[$key]->name;
$timestart = date("H:i", strtotime($file_content[$key]->timestart));
$timeend = date("H:i", strtotime($file_content[$key]->timeend));
$day = $file_content[$key]->day;
$reservations[] = array(
"name" => $name,
'timestart'=> $timestart,
'timeend'=> $timeend,
'day'=> $day
);
}
$reservations[] = array(
"name" => null,
'timestart'=> null,
'timeend'=> null,
'day'=> null
);
file_put_contents($file, json_encode($reservations));
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'henriks.php';
header("Location: http://$host$uri/$extra");
exit();
?>

can't you just output an empty Json string in it ?
file_put_contents('yourFile.json', json_encode([] /* empty array */))

use delete: delete $reservations[].name

Well it makes sense since you're json_encoding() an array which contains data ( $reservations), albeit with null values.
Assuming you want an empty array, this should do it.
file_put_contents('timetable.json', "[]");

Related

json_encode works for integers not for strings

I am trying to pass arrays from php to js and the json_encode function works on $MID (integer array) but fails to do anything on $name (array of strings).
Can anybody help me understand why it won't work?
$sql = "SELECT DISTINCT [materialID],[name],[categoryName],[materialResponsePerson]
FROM [SAP_Replication].[dbo].[IntranetProductResponsePerson]";
$params = array();
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$MID = array();
$name = array();
$cName = array();
$resPerson = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
array_push($MID,$row["materialID"]);
array_push($name,$row["name"]);
array_push($cName,$row["categoryName"]);
array_push($resPerson,$row["materialResponsePerson"]);
}
echo json_encode($MID); //works and returns values
echo json_encode($name); //returns bool(false)
sqlsrv_close($conn);
Only echo one thing back to the Javascript! It is expecting to get one reply from your PHP code and not 4.
so I would do
echo json_encode([ 'MID' => $MID,
'name' => $name,
'cName' => $cName,
'resPerson' => $resPerson
]);
Then change your js code to read data from the right object
I have made a mistake when commenting the code. When I var_dump the $name variable it returns bool(false). Later I found out that meant that json_encode doesn't support string which have 'đ','ž','...' in them so I need to convert the array to utf-8.
Thanks everyone for the help.

Json decode using content of array

I'm training myself (JSON and PHP) and I have a problem
I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/
So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills' for example) instead of [1]..[2]..
thanks for all your support
Use foreach and use if condition to check the name is 'total_kills' is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value for each stat with name using the if else statement.
Another way to do something with all objects in an array is to use the array_map() function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use.

Read data from JSON in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active
I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

Getting PHP array through AJAX

I want to create comments with AJAX, I do not know if this is the right way its my first time doing it. I have been searching google for hours and im really stuck.
What I want to achieve is to add a comment right after I click 'comment' button wihtout reloading the page.
I do not know how to create JSON array that will suit my needs.
This is my javascript:
$(function(){
var userComments = $('.userComments');
var commentsUrl="commentsLoad.php";
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
success: function(komentarji){
//$.each ...
userComments.append("output...");
},
error: function(e){
console.log(e);
}
});
});
This is my PHP:
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments=array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
header('Content-type: application/json');
echo json_encode($comments);
}
}
The path that you're on is almost perfectly paved. Except the following you need to take note of:
You should echo the result array in the JSON format outside the while loop.
Since you have specified the dataType as json in your ajax call (and telling jQuery that you are expecting json back from the server), $.ajax will handle the headers itself and therefore header('Content-type: application/json'); is not needed.
A little tweak on the assignment that you're doing on $comments array:
$comments[] = array( // without [] you'll always end up with ONE comment
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date']
);
Just as you have hinted subtly, you need to iterate the returned array and append each comment one-by-one:
success: function(komentarji){
var parsedComments = JSON.parse(komentarji); //parse the result to Javascript readable objects
$.each(parsedComments, function(){
userComments.append("id =>" + this.id + " name => " + this.name + " text =>" + this.text /* etc. */); //you can access each column key as javascript object key here
});
}, //...
Note: There is a typo in the array assignment that you're doing, just remove the ) on the line 'date' => $row['date']) and you'll be fine.
First of all, move the returning of data back to the javascript code out of the while loop so you only do it once. Then change the script a little so that each comment is added to a new occurrence in the $comments array.
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[] = array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
}
}
echo json_encode($comments);
exit;
You can't send more than one json output but you are sending one in each iteration of while loop
Also can't keep adding header
what you will be sending will look like
{"id": 3 , "name": "foo"}
{"id": 4 , "name": "bar"}
Note that there is no outer array wrapping these or comma separating them.
Thus they are invalid json when sent together.
Put all the comments into one array and send that instead
Try this:
include('config.php');
$comments = array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($comments, array('id' => $row['id'], 'name' => $row['name'], 'text' => $row['text'], 'date' => $row['date']));
}
return json_encode(array('status' => true, 'data' => $comments));
} else {
return json_encode(array('status' => false));
}
Also return status with response so that it will be easier to manipulate response

Slice a JSON string

I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.

Categories