如何使用PHP使用foreach循环遍历json对象?

时间:2017-04-05 05:51:03

标签: php json

如何使用每个人访问和打印参与者姓名。 Json对象是“参与者:名称”,并在使用标记化文件上传时填充。我知道标记化文件确实创建了一个成功的JSON obj。它在foreach循环内部给我带来了麻烦。

  

警告:非法偏移类型   第100行的C:\ xampp \ htdocs \ nkmoorth \ EthicsRound1.php

 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;
 }

2 个答案:

答案 0 :(得分:1)

1)$ json是你需要先解码它的字符串。

$json = json_decode($json);

2)你需要遍历对象并获得其成员

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

}

答案 1 :(得分:0)

您在此代码中提供了错误的索引

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