0

I need some help with my code, I am noob with JSON and PHP, but I`m learning

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

I have this JSON and this part of php code:

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

I have a wrong display of this code, but not how I want to be:

 213 | 26 31 

 212 | 22 33

Any help would be appreciated,thanks

1
  • 1
    Loop though $event rather than $ball Commented Dec 7, 2018 at 19:08

1 Answer 1

2

You need to make your inner foreach loop over the current event...

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

In case not all elements have this data, you can use the following...

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

Full code:

$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>
Sign up to request clarification or add additional context in comments.

4 Comments

Undefined index: balls and Invalid argument supplied for foreach(), not sure how what to fix
yes, I have extracted a part from the main JSON, it looks exactly...please have a look at my code: <table> <?php $url = 'url'; $data = file_get_contents($url); $json_post = json_decode($data,true); ?> <table><tr> <td><?php foreach ($event['balls'] as $ball) : ?> <?php echo $ball['ball']; ?> <?php endforeach; ?></td></tr> </table>
I've updated it to the full code I'm using. I think there were a few tags missing in your version (</td> etc)
Thank you Nigel for your time, you've been very helpful. Finally, it worked. Many thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.