2014-10-29 90 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