php
  • json
  • 2010-05-25 3 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) 결과 배열에서 검색하고 제거하는 부모 키를 찾을 필요가 있다고 생각하지만 어쨌든 stucked 해요.

    답변

    11

    json_decode은 중첩 된 배열로 구성된 PHP 구조로 JSON 객체를 변환합니다. 그런 다음 루프를 반복하면되고 싶지 않은 문자가 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

    +1

    키 이름을 모르는 경우 더 나은 솔루션이 아닙니다. – Sarfraz

    +0

    @moogeek :이 경우 "kind", "name", "weight"및 "age"를 의미합니까? 만약 당신이 그것을 모른다면, 당신은'$ value'을 반복하고 문자열에 대해 각각의 하위 값을 검사하면서 반복의 또 다른 계층을 도입 할 필요가있을 것입니다. 찾으면,'unset ($ animals [$ key])'는 위에서와 같이 작동 할 것이고, 그러면 루프에서 빠져 나올 수 있습니다. 내 대답에이 코드를 추가했습니다. –

    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); 
    
    ?> 
    
    관련 문제