Home > Enterprise >  JSON loop not printing expected results
JSON loop not printing expected results

Time:09-16

I have a JSON array I am trying to loop through and echo out certain bits.

A snippet of the full array can be seen here - https://pastebin.com/eCYcZWpV

This is the code I am using:

$str = file_get_contents('tst.json');
$json = json_decode($str, true);

       foreach($json['results'] as $item){
           
            foreach($item['vehicle'] as $data){
         
          echo $data['ownershipCondition'];
          echo "<br>";
          echo $data['registration'];
          echo "<br>";
          echo $data['vin'];
          echo "<br>";
          echo $data['make'];
          echo "<br>";
          echo $data['model'];
          echo "<br>";
          echo "<br>";
        }
    }

This is the expected outcome:

Used
ABC123
32847328474
Renault
Clio

Used
DEF123
48578435347589
Dacia
Sandeo
Clio

This is what I actually get along with a whole host of illegal string offset errors

U
U
U
U
U
U

H
H
H
H
H
H

V
V
V
V
V
V

R
R
R
R
R
R

C
C
C
C
C
C

CodePudding user response:

According to your sample data, $item['vehicle'] is an object, not an array. It only has a single set of data within it. Therefore you don't need the second foreach. Just access the properties more directly:

$str = file_get_contents('tst.json');
$json = json_decode($str, true);

foreach($json['results'] as $item){
       
  echo $item['vehicle']['ownershipCondition'];
  echo "<br>";
  echo $item['vehicle']['registration'];
  echo "<br>";
  echo $item['vehicle']['vin'];
  echo "<br>";
  echo $item['vehicle']['make'];
  echo "<br>";
  echo $item['vehicle']['model'];
  echo "<br>";
  echo "<br>";
}

P.S. In case you're wondering, the reason for the string offset errors is because by looping through $item["vehicle"], you're looping each property. So for example on the first loop it would find the "ownershipCondition" property, and puts its value into $data. So the first value provided for $data would be "Used", and clearly that's a string which doesn't have any properties such as "ownershipCondition", "registration", etc.

  • Related