使用 php 从 json 中删除元素

2022-08-30 22:47:44

对不起我的英语。我知道还有很多其他类似的问题,但我没有找到任何可以帮助我的东西(或者也许我不明白)。

我有一个像这样的json(autocaricate.json):

[
{
"nome":"LABORGHINI GALLARDO",
"descrizione":"LAMBORGHINI GALLARDO ED. NERA- ANNO 2007- ",
"indirizzo_pubblicato":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/LABORGHINI GALLARDO31072013-023853.json",
"indirizzo_immagine_copertina":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/IMG_1414 (600x448).jpg",
"indirizzo_paginaauto":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/index.html"
},
{
"nome":"RENAULT MEGANE",
"descrizione":"RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461",
"indirizzo_pubblicato":"autocaricateeea\/RENAULT MEGANE31072013-024103\/RENAULT MEGANE31072013-024103.json",
"indirizzo_immagine_copertina":"autocaricateeea\/RENAULT MEGANE31072013-024103\/P1080949 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/RENAULT MEGANE31072013-024103\/index.html"
},
{
"nome":"FORD MONDEO",
"descrizione":"FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-",
"indirizzo_pubblicato":"autocaricateeea\/FORD MONDEO31072013-045216\/FORD MONDEO31072013-045216.json",
"indirizzo_immagine_copertina":"autocaricateeea\/FORD MONDEO31072013-045216\/P1080971 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/FORD MONDEO31072013-045216\/index.html"
}
]

我想用php从json中删除一个元素(一辆汽车,例如雷诺MEGANE)。我写了一个这样的函数:

$url = $GET['indirizzo']; //this variable get an address like autocaricateeea\/RENAULT MEGANE31072013-024103\/index.html

$file = file_get_contents('autocaricate.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
foreach($data as $elemento) {
    $valore = $elemento['indirizzo_paginaauto'];
    if($valore == $url){
        ****** enter code here ******
    }
}
//save the file
file_put_contents('autocaricate.json',json_encode($data));
unset($data);//release memory

我应该编写哪些代码来从json文件中删除任何属性(对于我们要删除的汽车,例如雷诺MEGANE)?


答案 1

我已经找到了从JSON文件中检查和删除元素的正确方法。

$i=0;
foreach($data as $element) {
   //check the property of every element
   if($url == $element->indirizzo_paginaauto){
      unset($data[$i]);
      echo ("elemento cancellato");
   }
   $i++;
}

答案 2

这样做更容易。

//get all your data on file
$data = file_get_contents('teste_data.json');

// decode json to associative array
$json_arr = json_decode($data, true);

// get array index to delete
$arr_index = array();
foreach ($json_arr as $key => $value) {
    if ($value['YOUR KEY'] == SOME VALUE TO COMPARE) {
        $arr_index[] = $key;
    }
}

// delete data
foreach ($arr_index as $i) {
    unset($json_arr[$i]);
}

// rebase array
$json_arr = array_values($json_arr);

// encode array to json and save to file
file_put_contents('teste_data.json', json_encode($json_arr));

这将做得很好。相信我!


推荐