使用PHP从JSON显示多个条目

时间:2018-12-07 18:59:48

标签: php arrays json string parsing

我的代码需要帮助,我对JSON和PHP不满意,但是我正在学习

[
  {
 "eventId": 213,
"balls": [
  {
    "ball": 26,
    "id": 1
  },
  {
    "ball": 31,
    "id": 2
  }
]
  },
  {
"eventId": 212,
"balls": [
  {
    "ball": 22,
    "id": 1
      },
  {
    "ball": 33,
    "id": 2
  }
]
}
]

我有这个JSON和php代码的这一部分:

<table>
<?php
$url = 'external-link'; 

$data = file_get_contents($url);
$json_post = json_decode($data,true);
?>
    <table>
        <tbody>
        <?php foreach ($json_post as $event) : ?>
        <tr>
            <td><?php echo $event['eventId']; ?></td>
            <td><?php foreach ($json_post as $ball) : ?> <?php echo $ball['balls'][0]['ball']; ?> <?php endforeach; ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

此代码显示有错误,但不是我想要的样子:

 213 | 26 31 

 212 | 22 33

感谢您的任何帮助

1 个答案:

答案 0 :(得分:1)

您需要在当前事件上进行内部的foreach循环...

<td><?php foreach ($event['balls'] as $ball) : ?> <?php echo $ball['ball']; ?> <?php endforeach; ?></td>

如果不是所有元素都具有此数据,则可以使用以下...

    <td><?php if(isset($event['balls'])):
        foreach ($event['balls'] as $ball) : 
               echo $ball['ball']; 
        endforeach; 
        endif;?></td>

完整代码:

$url = "url";
$data = file_get_contents($url);
$json_post = json_decode($data,true);
?>
    <table>
        <tbody>
        <?php foreach ($json_post as $event) : ?>
        <tr>
            <td><?php echo $event['eventId']; ?></td>
            <td><?php if(isset($event['balls'])):
                foreach ($event['balls'] as $ball) : 
                       echo $ball['ball'].' '; 
                endforeach; 
                endif;?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>