How can I use foreach with JSON?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
cupboy
New php-forum User
New php-forum User
Posts: 8
Joined: Fri Aug 17, 2018 12:57 pm

Tue Sep 03, 2019 1:57 pm

Maybe it is not possible to use foreach. What other way can I read it.

Here is my code:

Code: Select all

<?php
try {
  $response = file_get_contents("http://localhost/REST2/RestController.php?view=wwmCompany");
  $assoc_array = true;
  $z = json_decode($response, $assoc_array);

  echo '>>>>'.$z; // >>>>[{"INTCOID":"56","INTCOCompanyName":"Jacks Appliance"},{"INTCOID":"94","INTCOCompanyName":"Jims Appliance"}]

  
  //foreach ($z as $k => $v) // Warning: Invalid argument supplied for foreach() in C:\asp\getcontents.php on line 14
  foreach ($z as $k[] => $v[]) // Warning: Invalid argument supplied for foreach() in C:\asp\getcontents.php on line 13
  {
    //echo $v[0]['INTCOID'];
    //echo $v['INTCOID'][0];
  }
} catch(Exception $err) {
  echo $err->getMessage();

}
?>
chorn
php-forum GURU
php-forum GURU
Posts: 611
Joined: Fri Apr 01, 2016 2:18 am

Tue Sep 03, 2019 10:38 pm

There's nothing wrong with using foreach

Code: Select all

<?php

  $response = '[{"INTCOID":"56","INTCOCompanyName":"Jacks Appliance"},{"INTCOID":"94","INTCOCompanyName":"Jims Appliance"}]'; // file_get_contents("http://localhost/REST2/RestController.php?view=wwmCompany");
  $assoc_array = true;
  $z = json_decode($response, $assoc_array);
  
  foreach ($z as $k => $v)
  {
    var_dump($k, $z);
  }
But using brackets within the foreach signature may lead to strange results.
Post Reply