<\/script>')

JSON Search and delete in 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 delete it (and json_encode again, as it was). How to do it? I think I need to search in the json_decode($_SESSION["animals"],true) resulting array and find the parent key to delete, but I'm stuck anyway.

+5
source share
3 answers

json_decode will turn a JSON object into a PHP structure consisting of nested arrays. Then you just need to go through them, and unset one you don't need.

 <?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); ?> 
+11
source

You have an extra comma at the end of the last element of your JSON. Remove it and json_decode will return the array. Just skip it, check the line, then undo the item when it is found.

If you need a final array with reindex, just pass it to array_values.

+3
source

This works for me:

 #!/usr/bin/env php <?php function remove_json_row($json, $field, $to_find) { for($i = 0, $len = count($json); $i < $len; ++$i) { if ($json[$i][$field] === $to_find) { array_splice($json, $i, 1); } } return $json; } $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"} }'; $decoded = json_decode($animals, true); print_r($decoded); $decoded = remove_json_row($decoded, 'name', 'Piranha the Fish'); print_r($decoded); ?> 
+2
source

Source: https://habr.com/ru/post/951651/


All Articles