php - 从json对象

时间:2017-01-17 18:54:07

标签: php arrays json object unset

我有一个包含以下数据的JSON文件:

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

现在我想取消其中一个设备。我已尝试使用以下PHP代码,但无法弄清楚为什么它不起作用:

$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));

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你应该

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

第一个foreach是因为你有多个对象,然后你去currnet对象中的每个设备并搜索它们是否具有指定的名称。 所以你搜索一个值并按键删除。