从JSON数组中完全删除JSON对象

时间:2018-09-18 14:18:12

标签: php json object unset

如果我通过PHP在JSON数组中设置了一些Obkect,那么我将得到一个带有两个空[]的未定义字段。但是我想删除没有[]的整个对象。

这是我正在使用的代码:

// Unset Data Object from JSON-File
unset($data['server'][$Server][$ID]['id']);
unset($data['server'][$Server][$ID]['svc']);

“未设置”之前的JSON文件:

{
  "server": {
    "SERVER-01": [
        {"svc":"SVC1", "id":1},
        {"svc":"SVC2", "id":2},
        {"svc":"SVC3", "id":3},
        {"svc":"SVC4", "id":4},
        {"svc":"SVC5", "id":5}
    ],
    "SERVER-02": [
        {"svc":"SVC1", "id":1},
        {"svc":"SVC2", "id":2},
        {"svc":"SVC3", "id":3},
        {"svc":"SVC4", "id":4},
        {"svc":"SVC5", "id":5}
    ]
  }
}

“未设置”后的JSON文件:

{
  "server": {
    "SERVER-01": [
        [],
        {"svc":"SVC2", "id":2},
        {"svc":"SVC3", "id":3},
        {"svc":"SVC4", "id":4},
        {"svc":"SVC5", "id":5}
    ],
    "SERVER-02": [
        {"svc":"SVC1", "id":1},
        {"svc":"SVC2", "id":2},
        [],
        {"svc":"SVC4", "id":4},
        {"svc":"SVC5", "id":5}
    ]
  }
}

编辑: 我通过unset($ data ['server'] [$ Server] [$ ID]获得以下输出:

{
  "server": {
    "SERVER-01": {
        "1": {"svc":"SVC2", "id":2},
        "2": {"svc":"SVC3", "id":3},
        "3": {"svc":"SVC4", "id":4},
        "4": {"svc":"SVC5", "id":5}
    },
    "SERVER-02": [
        {"svc":"SVC1", "id":1},
        {"svc":"SVC2", "id":2},
        {"svc":"SVC3", "id":3},
        {"svc":"SVC4", "id":4},
        {"svc":"SVC5", "id":5}
    ]
  }
}

1 个答案:

答案 0 :(得分:0)

代替这样做:

// Unset Data Object from JSON-File
unset($data['server'][$Server][$ID]['id']);
unset($data['server'][$Server][$ID]['svc']);

只需在ID处停下,就这样:

// Unset Data Object from JSON-File
unset($data['server'][$Server][$ID];

现在,当您json_encode数组时,您会看到它完全消失了:-)