我想从 php 中删除一个 pid 为 4 的 JSON 对象。 pid 是唯一值。如何实现这一点?
obdatabase.json
{"pobject":[{"pname":"Pikachu","pid":"1"},
{"pname":"squirtle","pid":"2"},
{"pname":"Justinbieber","pid":"3"},
{"pname":"Superman","pid":4}]}
删除.php
到目前为止,我的尝试。
<?php
$file="obdatabase.json";
$json = json_decode(file_get_contents($file),TRUE);
foreach ($json->pobjects as $pobject) {
if ($pobject->pid == 1) {
unset($pobject);
file_put_contents($file, json_encode($json));
}
}
?>
以下是使用数组过滤器如何完成此操作,以使用 PID 4 删除对象:
<?php
$file="obdatabase.json";
$json = json_decode(file_get_contents($file),FALSE);
function filterPID($var)
{
// returns whether the input integer is not 4
return(!($var->pid == 4));
}
$cleaned_array = array_filter($json, "filterPID");
?>
基于@Hiphop03199的替代解决方案:
$file="obdatabase.json";
$json = json_decode(file_get_contents($file), TRUE);
function filterPID($var)
{
return(!($var['pid'] == 4));
}
$cleaned_array = array_filter($json['pobject'], "filterPID");