JSON搜索并在PHP中删除?

moo*_*eek 6 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"}
}'; 
Run Code Online (Sandbox Code Playgroud)

例如,我想找到"Piranha the Fish"的行,然后将其删除(并将json_encode重新编码).这该怎么做?我想我需要在json_decode($_SESSION["animals"],true)结果数组中搜索并找到要移除的父键但是我仍然被卡住了.

Sam*_*war 12

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);
?>
Run Code Online (Sandbox Code Playgroud)