J Clark J Clark - 1 year ago 82
PHP Question

PHP Access JSON Array

Can't get json_decode to work here:

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

$data = json_decode($response);

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

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 Source

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

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

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download