How to loop through json Object using foreach usin

2020-05-09 22:08发布

How do I use for each to access and print the participant name. The Json object is "particpants:name" and it gets populated when uploaded with a tokenized file. I know the tokenized file does create a successful JSON obj. It is inside the foreach loop that gives me trouble.

Warning: Illegal offset type in C:\xampp\htdocs\nkmoorth\EthicsRound1.php on line 100

 protected function setMiddleHTML()
{
  //temp

  $this->html.='<div id="middleContainer">';
  $this->jsonObj = json_decode($_POST['fileContents']);
    $count=sizeOf($this->jsonObj->{'participants'}) -1;
  for($i =0; $i<$count; $i++) //should be numSections
   {
    $this->html .= '<tables class="section">';
      foreach($this->jsonObj->{'participants'} as $index => $value)
      {
      $this->html.='<td>' . $this->jsonObj->participants[$value].'</td> ';
      } // foreach
    $this->html .= '</table>';



  }// for    } // setMiddleHTML()

          $this->html.='</div>'; // closing middle Container;
 }

标签: php json
2条回答
\"骚年 ilove
2楼-- · 2020-05-09 22:37

1) $json is a string you need to decode it first.

$json = json_decode($json);

2) you need to loop through the object and get its members

foreach($json as $obj){
   echo $obj->name;
   .....

}
查看更多
▲ chillily
3楼-- · 2020-05-09 22:45

You are supplying the wrong index in this code

foreach($this->jsonObj->{'participants'} as $index => $value)
{
    // $this->html.='<td>' . $this->jsonObj->participants[$value].'</td> ';

    // instead
    $this->html.='<td>' . $this->jsonObj->participants[$index].'</td> ';

    //or
    //$this->html.='<td>' . $value.'</td> ';

} // foreach
查看更多
登录 后发表回答