【发布时间】:2026-01-04 06:40:01
【问题描述】:
我有一个包含以下数据的 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));
提前感谢您的帮助!
【问题讨论】:
-
您要取消设置哪个键?
$_POST['name']的值是多少? -
$_POST['name'] 是设备的名称。
标签: php arrays json object unset