Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php从json中删除记录_Php_Json - Fatal编程技术网

使用php从json中删除记录

使用php从json中删除记录,php,json,Php,Json,我想通过在提交之前将状态更改为delete,从JSON中删除一条记录 JSON: 我从JSON上读到的很好: $data_url = 'data.json'; $data_json = file_get_contents($data_url); $data_array = json_decode($data_json, true); //plus a bunch of _GET stuff here... ... // then write to JSON like so $data[$nam

我想通过在提交之前将
状态更改为delete,从JSON中删除一条记录

JSON:

我从JSON上读到的很好:

$data_url = 'data.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
//plus a bunch of _GET stuff here...
...

// then write to JSON like so
$data[$name] = array(
    'name' => $name,
    'title' => $title,
    'photo_url' => $photo_url,
    'status' => $status
    );

//EDIT - this is my feeble attempt
if($status == 'DELETE'){
    unset($data[$name]);
};
//END EDIT

// merge and write array to json    
$data_array = array_merge($data_array, $data);
file_put_contents('data.json', json_encode($data_array, JSON_FORCE_OBJECT));

但是我不知道如何删除记录…

正如我所看到的,您正在尝试在php中删除json的一部分

您可以使用以下代码:

foreach($data as $key=>$val){
   // check status
   if ($val["status"]=="DELETE"){
      // this deletes record from array
      unset($data[$key]);
   }
}

file_put_contents('data.json', json_encode($data, JSON_FORCE_OBJECT));

在对数据进行json_解码以删除状态为“delete”的键之后,我看不到有人试图操纵$data_数组。您也不需要JSON_FORCE_对象,因为您在解码调用中强制数据_数组成为关联数组。甚至没有削弱它…马尔科的答案看起来不错。正如他指出的,您需要检查数据(foreach)中的每个项,检查该项的状态是否设置为DELETE,如果设置为DELETE,则从数据中删除该项。
foreach($data as $key=>$val){
   // check status
   if ($val["status"]=="DELETE"){
      // this deletes record from array
      unset($data[$key]);
   }
}

file_put_contents('data.json', json_encode($data, JSON_FORCE_OBJECT));