如何通过php中的唯一ID删除Json

时间:2016-02-15 03:12:45

标签: 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="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));
    }
}
?>

2 个答案:

答案 0 :(得分:0)

以下是使用array-filter完成的方法,用于删除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");

?>

答案 1 :(得分:0)

基于@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");