2

I have this json response

 {"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]}

All I need is to extract the random1,random2,random,3 from response so the final results will be:

  • random1
  • random2
  • random3

I have this script

$jsonData = file_get_contents("json");

$json = json_decode($jsonData,true); 

foreach($json["results"][0]["response"] as $data) {
 {
   echo json_encode($data);

}
}

But this will extract only

  • random1

If I change [0] in [1] will extract the random2 and [2] random3 How can I get random1,random2,random3, response at once? so the final echo will be:

  • random1
  • random2
  • random3

Thank you in advance, any help would be appreciated!

3 Answers 3

3

Loop at your $json['result'] what your doing is only taking the first index 0 which have random1 as its response value

$json = '{"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]}';
$json = json_decode($json,true); 

foreach($json["results"] as $data) {
   echo $data['response'][0]."\n";
}

Try it here


Update

if you want to filter let's say random1 then do like this

$json = json_decode($json,true); 
$filter = array("random1"); //You can add items to filter
$result = array();
foreach($json["results"] as $data) {
   if(!in_array($data['response'][0],$filter))
       $result[] = $data;
}
print_r($result);

$result will contain only random2 & random3

Sign up to request clarification or add additional context in comments.

9 Comments

@AlexandruVorobchevici No problem. glad i helped. Make sure to accept answers for future references and help others with the same problem.
Is any change to insert a word filter in this? so I can filter some words I have tried with if(strpos($data, 'random1') !== false) but won't work
@AlexandruVorobchevici what kind of words? random1 to random3?
Let's say I wanna filter random1.. so the final result will be random2 and random3
Fixed with foreach($json["results"] as $data) { if(preg_match('/^(badword)$/i',$data['results'][0])) continue; echo $data['answers'][0]."\n"; } Thank you again for your help!
|
0

results is an array, so you got the first one in the array by this: $json["results"][0].

If you want to iterate all the values, it should be like this:

foreach($json["results"] as $data) {
   echo json_encode($data['response']);

}

Comments

0
foreach($json["results"] as $data) {    echo json_encode($data['response']);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.