remove quote from array without using JSON_NUMERIC

2019-08-08 10:53发布

问题:

I am trying to plot a scatter plot using highcharts.

Javascript code:

<script type='text/javascript'>
\$(function () {
var chart;
\$(document).ready(function() {
   chart = new Highcharts.Chart({
        chart: {
            renderTo: '$div_id',
            type: 'scatter',
            zoomType: 'xy',                
            marginRight: 450,
            marginBottom: 75
        },
...
...
       series: [{
             name: 'name1',
             data: $data    
       }]
     });
   }); 
});
</script>";

My php code:

$data_array4 =  mysql_query("SELECT * from table", $link);
$ret1 = array();
while($item = mysql_fetch_array($data_array4)) {
    $La = $item['L'];
    $Ge = $item['G'];
    $ret1[] = array($La,$Ge);
}
$data = json_encode($ret1);

My data looks like:

data: [["0.457","0.02"],["0.464","0.02"],["0.469","0.01"],["0.469","0.01"]]

The chart didn't show up because the double quotes. How can I remove them without using $data = json_encode($ret1,JSON_NUMERIC_CHECK), I am on PHP 5.2, cannot use that parameter.

Thanks!

回答1:

It seems you didn't figure it out from the comments just. But of course you need to convert both strings to real numbers:

$La = (float) $item['L'];
$Ge = (float) $item['G'];
$ret1[] = array($La,$Ge);

Else the resulting list will contain one string and one number, resulting in a JSON object/map instead of a list.

Your next question: Yes, floats are inprecise and not always as short as the original string representation.



回答2:

You could convert each value to a number using floatval

$num = floatval("5.125");

http://us3.php.net/manual/en/function.floatval.php

You could also loop around the array in JavaScript and use parseFloat...

var num = parseFloat("5.125");