php
  • json
  • 2010-05-25 33 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); 
    
    ?> 
    
    相關問題