0

Here's the json

{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}

Here's my code

$json = json_decode($data);
foreach($json["result"] as $result){
    foreach($result["files"] as $file){
        echo $file["file_code"];
    }
}

I want to extract all values from the "file_code". I got an error Warning: Invalid argument supplied for foreach()

I was able get the VALUE of the first one using

echo $json->result->files[0]->file_code;

Is it possible to use a LOOP for the files[0]?

Gir brodly
  • 11
  • 3

3 Answers3

0

I replicated your situation and it turns out that your JSON is invalid. You're missing a } at the end.

The reason for not getting an exception is because json_decode does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR flag, read the docs for more info.

renshul
  • 95
  • 1
  • 7
0

This works perfect for me. If you have any thoughts please feel free to correct me.

$num = count($json->result->files);
echo $num;

for($i=0;$i<$num;$i++)
    {
echo $json->result->files[$i]->file_code;
    }
Gir brodly
  • 11
  • 3
0

This line:

foreach($json["result"] as $result){

sees $json['result'] as an object, and so the next line tests for total_pages["files"], which doesn't exist.

Putting both foreach's together solves the problem:

$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}';

$json = json_decode($data, true);
foreach($json["result"]["files"] as $file)
        print $file["file_code"];

Teh playground

Alternatively, make the JSON result into an array, and use object property accessors instead of associative array bindings.

$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":[{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}]}';
$json = json_decode($data);
foreach($json->result as $result){
    foreach($result->files as $file){
        echo $file->file_code;
    }
}

Teh playground

JMP
  • 4,417
  • 17
  • 30
  • 41