[英]How to update (overwrite) a json file using php
[
{
"id" : 1,
"name" : "levin",
"description" : "some desc",
"size" : "100KG",
"actions" : {
"walking" : true,
"eating" : true
}
},
{
"id" : 2,
"name" : "clara",
"description" : "some desc",
"size" : "2000KG",
"actions" : {
"walking" : false,
"eating" : true
}
}
]
This is my person.json file. 这是我的person.json文件。 I like to update(overwrite) existing values.
我喜欢更新(覆盖)现有值。 Am not found any useful questions regarding this.
找不到与此有关的任何有用问题。
i have a name "levin" i like to overwrite it to empty or "---". 我有一个名字“ levin”,我想将其覆盖为空或“ ---”。 But its should only based through "id" .Following is my php code but its not working :(
但它只能基于“ id”。以下是我的PHP代码,但不起作用:(
public function api_put()
{
//print($this->put('id')); am getting here 2 value from other page
//print($this->put('action'));.
if($this->put('action') == "remove"){
$file = json_decode(file_get_contents("assets/json/person.json"));
$new_val = array();
$i = 0 ;
foreach ($file as $key => $value) {
if((string)$value->id == $this->put('id')) {
$data[] = (string)$value->name="--";(string)$value->description="--";
$new_val[$i] = $data;
$i++;
}
}
file_put_contents('assets/json/person.json', json_encode($new_val));
$message = array('id' => $this->put('id'), 'message' => 'Successfully updated!!');
$this->response($message, 200);
}
}
How can i overwrite a json value depend upon a particular id and with out change all other id data. 我如何才能覆盖一个json值取决于一个特定的id,而不会更改所有其他id数据。 am using codeigniter REST api.
我正在使用codeigniter REST api。 thanks in advance
提前致谢
A couple of things. 有几件事。
$new_val
array, you can just edit these resources in place. $new_val
数组,只需就地编辑这些资源。 (string)$value->id == $this->put('id')
is not necessary. (string)$value->id == $this->put('id')
。 The PHP engine will do this conversion for you. (string)$value->description="--";
That statement has no effect. (string)$value->name="--";(string)$value->description="--";
(string)$value->name="--";(string)$value->description="--";
Two statements doing two operations should be on two different lines. public function api_put()
{
if ($this->put('action') == 'remove')
{
$file = json_decode(file_get_contents('assets/json/person.json'));
foreach ($file as $key => $value)
{
if ($value->id == $this->put('id'))
{
$value->name = '--';
$value->description = '--';
}
}
file_put_contents('assets/json/person.json', json_encode($file));
$message = array('id' => $this->put('id'), 'message' => 'Successfully updated!!');
$this->response($message, 200);
}
}
There, isn't that much nicer? 在那里,不是更好吗?
I think you must need to loop like this to store all details 我认为您必须像这样循环以存储所有详细信息
foreach ($file as $key => $value) {
if((string)$value->id == $this->put('id')) {
$value->name="--";(string)$value->description="--";
}
$new_val[$i] = $value;
$i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.