Mark.S
Mark.S

Reputation: 165

unable to get last value of JSON array in PHP

here is the JSON file in question. I need to get the last y value from the values array. This updates once a day so the code below is what I've tried, but won't update to the latest value:

<?php
$url = 'https://api.blockchain.info/charts/avg-block-size?format=json';
$data = file_get_contents($url);
$stats = json_decode($data, true);

$blocksize = $stats['values']['363']['y'];

echo $blocksize;
?>

thoughts?

Upvotes: 0

Views: 612

Answers (2)

Kartik Prasad
Kartik Prasad

Reputation: 740

You can count the array size and -1 from it

$blocksize = $stats['values'][count($stats['values']) - 1]['y'];

Upvotes: 1

John Ellmore
John Ellmore

Reputation: 2229

Try using:

$lastValue = end($stats['values']);
$blocksize = $lastValue['y'];

Upvotes: 4

Related Questions