I have an array that is used later used by jquery to plot a chart (hence the json_encode).
<?php
$server = "myserver:1234";
$user="dbuser";
$password="userpass";
$database = "dbname";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT Y FROM listener_incr";
$result = mysql_query($query);
$i = -60;
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($i,$row['Y']);
$i++;
}
$final = json_encode($dataset1,JSON_NUMERIC_CHECK);
?>
The output of $final is [[-60,5],[-59,3],[-58,6],...[-1,7],[0,8]]
Aside from the data series being used to plot a chart, I want to echo the last value of my array to a div.
Here is what I have tried...
<div id="LastInArray">
Current count: <?php
end($dataset1);
$intOutput = key($dataset1);
echo $intOutput;
?>
</div>
But the above outputs Current count: 59
, which I don't understand. The output I want for the div (in this example) is Current count: 8
.
Later I want to use AJAX to update this value, which is why it's in a div.
end()
doesn't traverse your multi-dimensional array iirc. For your value something like $dataset1[count($dataset1)-1][1]
should be enough.
Use array_pop
Check the documentation http://php.net/manual/en/function.array-pop.php
$tmp = current($dataset1); // return [-1, 8]
$intOutput = $tmp[1]; // return 8
You can always count() the number of records in the array and then access its last record with count()-1.
I would suggest you to find out the JSON length first and then using length-1 as key, you can get the value out of key-value pair in JSON.