J Clark J Clark - 5 months ago 20
PHP Question

PHP Access JSON Array

Can't get json_decode to work here:

<?php
$response = wp_remote_get( 'http://data.dnr.ne.gov/RealTime/api/6881500/2016/3/8/Discharge' );

$data = json_decode($response);
?>

<table>
<tr>
<th><?php echo $data[0]; ?></th>
</tr>
</table>


var_dump($response); spits out the whole json object, so the API call is working fine.

Any help even accessing element 0 will be fantastic!

Answer

$data[0] is an object (of type stdClass). It can be an array if you pass TRUE as the second argument to json_decode().

Either way, echo cannot display its content. You have to ask it to display the properties (if it's an object) or values (if it's an array) of $data[0] to get the information you want.

F.e., using the code you posted, it would be something like:

<table>
  <tr>
    <th>Station number</th>
    <th>Date</th>
    <th>Value/th>
  </tr>
  <?php foreach ($data as $row) { ?>
  <tr>
    <td><?php echo($row->stationNumber); ?></td>
    <td><?php echo($row->date); ?></td>
    <td><?php echo($row->value); ?></td>
  </tr>
  <?php } ?>
</table>

If you decode the JSON to arrays ($data = json_decode($response, TRUE);), then change the display of the data as follows:

<td><?php echo($row['stationNumber']); ?></td>
<td><?php echo($row['date']); ?></td>
<td><?php echo($row['value']); ?></td>
Comments