2014-10-29 65 views
-1

刪除元素我要搜索字符串中的JSON和刪除它,但我的代碼不能正常工作,PHP - 搜索字符串,並以JSON

JSON的這個例子:

{ 
    d: { 
    results: [ 
       { 
       name: "first", 
       Url: "http://example.com/tes.pdf" 
       }, 
       { 

       name: "second", 
       Url: "http://example.com/download/qwdahfvajvlaksjkjdfaklfaf" 
      } 
      ] 
    } 
} 

,這我PHP代碼:

$result = file_get_contents("cache.json"); 
$jsonObj = json_decode($result); 
foreach($jsonObj->d->results as $key => $value) { 
    if(strpos($value->Url, '.pdf') !== true) { 
     unset($key->$value); 
    } 

} 
echo json_encode($jsonObj); 
在這種情況下

,我想刪除元素第二不包含網址 「.PDF」,

任何人都可以幫助我?

+1

不是有效的json檢查http://jsonlint.com/ – 2014-10-29 10:38:01

回答

0

試試這個:

$result = '{"d":{"results":[{"name": "first","Url": "http://example.com/tes.pdf"},{"name": "second","Url": "http://example.com/download/qwdahfvajvlaksjkjdfaklfaf"}]}}'; 
$jsonArr= json_decode($result, true); //this is an array 


foreach($jsonArr['d']['results'] as $key => $value) { 
    if(strpos($value['Url'], '.pdf') !== false) { 
     continue; //found so not interested in it 
    } else { 
     unset($jsonArr['d']['results'][$key]); 
    } 

} 
echo json_encode($jsonArr); 

當我與鍵和值的工作,我想轉換(如果需要)它到一個數組。這很容易理解和操縱。

希望這會有所幫助! :D

+1

讓我們試着保留評論集中在一個職位的*技術優點*,請。由於小錯誤已經修復,我刪除了評論。 – 2014-10-29 14:52:05

+0

@AndrewBarber非常感謝George Garchagudashvili,感謝您對該修復的意見。 – 2014-10-29 15:05:11

-1

最好的辦法是使用json_decode()將其轉換爲數組;從那裏,你可以迭代你的數組。如果它停留在相同的結構,然後像下面應該工作:

<?php 
    $a = $array['d']['results']; 
    foreach($a as $b => $c) { 
     if(strpos($c['Url'], '.pdf') !== FALSE) { 
      // Found 
     } else { 
      unset($a[$b]); // Unset in original array. 
     } 
    } 
+0

看起來一個有效的json? – 2014-10-29 10:38:44

+0

對不起?他們的JSON是無效的,但我認爲他們打字時不會複製它,因爲唯一的問題是鍵沒有被製成字符串。 – Bowersbros 2014-10-29 10:40:04

+0

不承擔總是檢查什麼OP發佈,如果任何錯過建議更正 – 2014-10-29 10:41:01