Php 从JSON数据中删除特定节点
我想使用PHP从JSON文件中删除一个特定节点 目前我正在使用以下PHP代码:Php 从JSON数据中删除特定节点,php,json,Php,Json,我想使用PHP从JSON文件中删除一个特定节点 目前我正在使用以下PHP代码: <?php $file = 'data2.json'; $json_data = file_get_contents($file); $json = json_decode($json_data, true); foreach ($json as $key => $value) { if ($value['id']=='ajson2') { unset ($value[$key
<?php
$file = 'data2.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data, true);
foreach ($json as $key => $value) {
if ($value['id']=='ajson2') {
unset ($value[$key]);
}
echo json_encode($json);
}
?>
但目前它不会从JSON数据中删除节点。您应该这样使用
$file = 'ico1.json';
$json = json_decode(file_get_contents($file),true);
foreach ($json as $key => &$value) {
$sKey = array_search('ajson2', $value);
if ($sKey!==false) {
unset($value[$sKey]);
}
}
$json = json_encode($json);
如果不使用true作为json\u decode
的第二个参数,它将返回一个对象正确的代码是:
<?php
$file = 'data2.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data, true);
foreach ($json as $key => $value) {
if ($value['id']=='ajson2') {
unset ($json[$key]);
}
file_put_contents($file, json_encode($json));
}
?>
您必须从阵列中取消设置$value是存储在$json数组的$key索引中的数据。未设置($json[$key]);这两个选项都没有帮助,对不起,我已经尝试过这个代码,它工作得很完美,你到底打到了哪里?什么是o/P我不太清楚。更改了下面所述的描述,您肯定应该更改“unset($value[$key]);”到“unset($json[$key]);”。若要再次检查,请在foreach循环之外使用您的“echo”。不,它不起作用。无论如何,这里有正确的代码:'
<?php
$file = 'data2.json';
$json_data = file_get_contents($file);
$json = json_decode($json_data, true);
foreach ($json as $key => $value) {
if ($value['id']=='ajson2') {
unset ($json[$key]);
}
file_put_contents($file, json_encode($json));
}
?>