从JSON数据中删除特定节点

时间:2014-05-12 09:03:58

标签: php json

我想使用PHP从我的JSON文件中删除特定节点。

目前我正在使用以下PHP代码:

<?php
$file = 'data2.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data, true);

foreach ($json as $key => $value) {
    if ($value['id']=='ajson2') {
         unset ($value[$key]);
    }
    echo json_encode($json);
}
?>

并拥有以下JSON数据:

[
    {
        "id": "ajson0",
        "parentNode": "add",
        "name": "Root",
        "type": "folder"
    },
    {
        "id": "ajson2",
        "parentNode": "ajson0",
        "name": "ggg",
        "type": "test"
    },
    {
        "id": "ajson3",
        "parentNode": "ajson0",
        "name": "dvvd",
        "type": "test"
    }
]

但目前它不会从JSON数据中删除该节点。

2 个答案:

答案 0 :(得分:0)

你应该这样使用,

$file = 'ico1.json';
$json = json_decode(file_get_contents($file),true);
foreach ($json as $key => &$value) {

$sKey = array_search('ajson2', $value);
if ($sKey!==false) {
    unset($value[$sKey]);
}
}
$json = json_encode($json);

如果你不使用true作为json_decode的第二个参数,它将返回一个对象

答案 1 :(得分:0)

正确的代码是:

<?php
$file = 'data2.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data, true);
foreach ($json as $key => $value) {

        if ($value['id']=='ajson2') {
            unset ($json[$key]);
        }

    file_put_contents($file, json_encode($json));
}
?>