Search code examples
phparraysjsonobjectunset

php - delete by value from json object


I've got a JSON file with following data:

{
    "0": {
        "name": "Test1",
        "devices": [
          {
              "name": "Test1",
              "code": "654345",
              "state": "on"
          },
          {
              "name": "Test2",
              "code": "876543",
              "state": "off"
          },
          {
              "name": "Test3",
              "code": "44444",
              "state": "off"
          }
        ]
     },
     "1": {
         "name": "Test2",
         "devices": [
           {
              "name": "Test4",
              "code": "987654",
              "state": "on"
           }
         ]
     }
}

Now I want to unset one of the devices. I've tried it with following PHP code, but can't figure out why it won't work:

$file = '../data/data.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data);

foreach ($json as $key => $value) {
    foreach ($value->devices as $k => $v) {
        if ($v->name == $_POST["name"]) {
            unset($json[$key]);
        }
    }
}

file_put_contents($file, json_encode($json));

Thanks in advance for any help!


Solution

  • You should

    unset($json->$key->devices[$k]);
    

    First foreach is because you have multiple objects, then you go for each devices in the currnet object and search if they have that specified name. So you search for a value and delete by key.