Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Search and remove in php?

Tags:

json

php

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"}
}'; 

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.

like image 928
moogeek Avatar asked May 25 '10 02:05

moogeek


1 Answers

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);
?>
like image 141
Samir Talwar Avatar answered Sep 28 '22 10:09

Samir Talwar