Javascript 如何从php中通过唯一ID删除Json
我想从php中删除一个pid为4的JSON对象。pid是唯一的值。如何做到这一点 obdatabase.jsonJavascript 如何从php中通过唯一ID删除Json,javascript,php,jquery,html,json,Javascript,Php,Jquery,Html,Json,我想从php中删除一个pid为4的JSON对象。pid是唯一的值。如何做到这一点 obdatabase.json {"pobject":[{"pname":"Pikachu","pid":"1"}, {"pname":"squirtle","pid":"2"}, {"pname":"Justinbieber","pid":"3"}, {"pname":"Superman","pid":4}]} delete.php 我到目前为止的努力 <?php $file="obdataba
{"pobject":[{"pname":"Pikachu","pid":"1"},
{"pname":"squirtle","pid":"2"},
{"pname":"Justinbieber","pid":"3"},
{"pname":"Superman","pid":4}]}
delete.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");
?>
替代解决方案基于:
签出-它允许您创建一个函数,该函数根据它返回的布尔值确定哪些内容保留在数组中,哪些内容不保留在数组中。除非在json中使用
TRUE
,否则解码将使整个结构数组,而不是objectsGood point。我猜想询问者的意图是错误的,因为他在代码中引用了->pid。[Edit answer to fix]或OP未意识到问题。第二个参数不需要,因为FALSE
是默认值。我不确定是什么意图意识到它是一个可选参数,为了让OP更清楚,我把它放在那里了。或者类似的东西
$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");