php
  • json
  • 2010-05-25 60 views 5 likes 
    5

    我有一个包含有值的深JSON对象会话变量$_SESSION["animals"]:再次JSON在php中搜索并删除?

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

    例如,我想找到与“食人鱼鱼”的行,然后将其删除(和json_encode它,因为它是)。 如何做到这一点?我想我需要在json_decode($_SESSION["animals"],true)搜索结果数组,并找到父键删除,但我无论如何被困住。

    回答

    11

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

    谢谢!如果我不知道关键的名字,怎么做? – moogeek 2010-05-25 02:24:43

    +1

    如果不知道密钥名称,这不是更好的解决方案。 – Sarfraz 2010-05-25 02:26:19

    +0

    @moogeek:在这种情况下,你的意思是“善良”,“名称”,“体重”和“年龄”?如果你不知道,你需要引入另一层迭代,循环'$ value'并检查每个子值与你的字符串。如果你发现它,'unset($ animals [$ key])'会像上面那样工作,然后你就可以跳出循环。我已将此代码添加到我的答案中。 – 2010-05-25 02:38:52

    3

    您在JSON中最后一个元素的末尾添加了逗号。删除它并json_decode将返回一个数组。简单地循环,测试字符串,然后在找到时取消设置元素。

    如果您需要最终数组重新编制索引,只需将它传递给array_values即可。

    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); 
    
    ?> 
    
    相关问题