JSON搜索并在php中删除? [英] JSON Search and remove in php?
问题描述
我有一个会话变量$_SESSION["animals"]
,其中包含一个具有值的深json对象:
I have a session variable $_SESSION["animals"]
containing a deep json object with values:
$_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)
结果数组中搜索并找到要删除的父键,但是我还是被卡住了.
For example, I want to find the line with "Piranha the Fish" and then remove it (and json_encode it again as it was).
How to do this? I guess i need to search in json_decode($_SESSION["animals"],true)
resulting array and find the parent key to remove but i'm stucked anyways.
推荐答案
json_decode
会将JSON对象转换为由嵌套数组组成的PHP结构.然后,您只需要遍历它们,然后unset
不需要的遍历.
json_decode
will turn the JSON object into a PHP structure made up of nested arrays. Then you just need to loop through them and unset
the one you don't want.
<?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);
?>
这篇关于JSON搜索并在php中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!