<?php $JSON = '{"Results":[' . '{"username":"test","password":"test"},' . '{"username":"test","password":"test"},' . '{"username":"google","password":"test"},' . '{"username":"yahoo","password":"test"},' . '{"username":"hotmail","password":"test"}' . ']}'; // use json_decode to parse the JSON data in to a PHP object $jsonInPHP = json_decode($JSON); // now iterate over the results and remove the one that google $results = count($jsonInPHP->Results); for ($r = 0; $r < $results; $r++){ // look for the entry we are trying to find if ($jsonInPHP->Results[$r]->username == 'google' && $jsonInPHP->Results[$r]->password == 'test'){ // remove the match unset($jsonInPHP->Results[$r]); // now we can either break out of the loop (only remove first match) // or you can use subtract one from $r ($r--;) and keep going and // find all possible matches--your decision. break; } } // now that we removed items the keys will be off. let re-order the keys // so they're back in-line $jsonInPHP->Results = array_values($jsonInPHP->Results); // dump the new JSON data, less google entry echo json_encode($jsonInPHP);
It would be the way I approach him. I like to avoid foreach(...){} when I need to modify the array itself. The above code, by the way, leaves you:
{ "Results":[ {"username":"test","password":"test"}, {"username":"test","password":"test"}, {"username":"yahoo","password":"test"}, {"username":"hotmail","password":"test"} ] }
source share