Wednesday, 15 May 2013

PHP - Search String And Remove Element in Json -



PHP - Search String And Remove Element in Json -

i want search string in json , remove it, code doesn't work,

this illustration of json :

{ d: { results: [ { name: "first", url: "http://example.com/tes.pdf" }, { name: "second", url: "http://example.com/download/qwdahfvajvlaksjkjdfaklfaf" } ] } }

and php code :

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

in case, want remove element second not contain url ".pdf",

anyone can help me?

try this:

$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 array foreach($jsonarr['d']['results'] $key => $value) { if(strpos($value['url'], '.pdf') !== false) { continue; //found not interested in } else { unset($jsonarr['d']['results'][$key]); } } echo json_encode($jsonarr);

when work keys , values, convert (if needed) array. it's easier understand , manipulate.

hope helps! :d

php json

No comments:

Post a Comment