-1

If i unset some Obkects in a JSON-Array via PHP, then i get an undefined Field with two empty []. But i want to delete the whole Object without [].

This is the Code I am using:

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

JSON-File before "unset":

{
  "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-File after "unset":

{
  "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}
    ]
  }
}

EDIT: The following Output i get with 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}
    ]
  }
}
danielx78
  • 41
  • 4

1 Answers1

0

Instead of doing this:

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

Just stop at the ID, like this:

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

Now when you json_encode your array, you'll see it 's completely gone :-)

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
  • If i do this, then i get a complete different JSON-File -> see edited Question – danielx78 Sep 18 '18 at 14:42
  • 1
    I had to add the new data to a new array and then reencode this array: $var=array(); foreach($data['server'][$Server] as $key => $item) { $var['server'][$Server][] = $item; } echo json_encode($var, JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK), "\n\n\n"; – danielx78 Sep 20 '18 at 12:33
  • Glad you got there! Have a great day :-) – delboy1978uk Sep 20 '18 at 12:40