JSON搜索并在PHP中删除?

时间:2010-05-25 02:13:00

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

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

3 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分:3)

在JSON的最后一个元素的末尾有一个额外的逗号。删除它,json_decode将返回一个数组。只需循环遍历它,测试字符串,然后在找到时取消设置元素。

如果您需要重新编制索引的最终数组,只需将其传递给array_values

答案 2 :(得分:2)

这对我有用:

#!/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);

?>