【问题标题】:JSON Search and remove in php?JSON在php中搜索和删除?
【发布时间】:2011-02-23 11:59:34
【问题描述】:

我有一个会话变量$_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) 结果数组中搜索并找到要删除的父键,但我还是被卡住了。

【问题讨论】:

    标签: php json


    【解决方案1】:

    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);
    ?>
    

    【讨论】:

    • 谢谢!如果我不知道键名怎么办?
    • 如果不知道密钥名称,这不是更好的解决方案。
    • @moogeek:在这种情况下,您是指“种类”、“姓名”、“体重”和“年龄”吗?如果您不知道,则需要引入另一层迭代,循环通过$value 并根据您的字符串检查每个子值。如果你找到它,unset($animals[$key]) 将像上面那样工作,然后你可以跳出循环。我已将此代码添加到我的答案中。
    • 我刚刚意识到使用in_array 会容易得多。详情见我的回答。
    【解决方案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);
    
    ?>
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多