JSON搜索并在php中删除? [英] JSON Search and remove in php?

查看:96
本文介绍了JSON搜索并在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆