一尘不染

JSON搜索并在php中删除?

json

我有一个会话变量,$_SESSION["animals"]其中包含带有值的深层json对象:

$_SESSION["animals"]='{
"0":{"kind":"mammal","name":"Pussy the Cat","weight":"12kg","age":"5"},
"1":{"kind":"mammal","name":"Roxy the Dog","weight":"25kg","age":"8"},
"2":{"kind":"fish","name":"Piranha the Fish","weight":"1kg","age":"1"},
"3":{"kind":"bird","name":"Einstein the Parrot","weight":"0.5kg","age":"4"}
}';

例如,我想找到带有“ Piranha the
Fish”的行,然后将其删除(并再次对其进行json_encode)。这该怎么做?我想我需要在json_decode($_SESSION["animals"],true)结果数组中搜索并找到要删除的父键,但是我还是被卡住了。


阅读 195

收藏
2020-07-27

共1个答案

一尘不染

json_decode会将JSON对象转换为由嵌套数组组成的PHP结构。然后,您只需要遍历它们和不需要unset的一个即可。

<?php
$animals = '{
 "0":{"kind":"mammal","name":"Pussy the Cat","weight":"12kg","age":"5"},
 "1":{"kind":"mammal","name":"Roxy the Dog","weight":"25kg","age":"8"},
 "2":{"kind":"fish","name":"Piranha the Fish","weight":"1kg","age":"1"},
 "3":{"kind":"bird","name":"Einstein the Parrot","weight":"0.5kg","age":"4"}
 }';

$animals = json_decode($animals, true);
foreach ($animals as $key => $value) {
    if (in_array('Piranha the Fish', $value)) {
        unset($animals[$key]);
    }
}
$animals = json_encode($animals);
?>
2020-07-27